leetcode第一天
阿新 • • 發佈:2017-12-26
eas -- 序列 num type lee cnblogs def ++
leetcode 第一天
2017年12月24日
第一次刷leetcode真的是好慢啊,三道題用了三個小時,而且都是簡單題。
數組
1.(674)Longest Continuous Increasing Subsequence
JAVA
class Solution { public int findLengthOfLCIS(int[] nums) { int tem = 1 , length = 1; if(nums.length==0) return 0; for (int i = 0;i<nums.length -1;i++){ if ( nums[i+1] - nums[i] > 0){ tem ++; length = Math.max(tem,length); }else{ tem = 1; } } return length; } }
Python
class Solution(object): def findLengthOfLCIS(self, nums): """ :type nums: List[int] :rtype: int """ max_len = tem_len = 1 if len(nums)==0: return 0 for i in range(len(nums)-1): if nums[i+1] >nums [i]: tem_len += 1 max_len = max(tem_len,max_len) else: tem_len = 1 return max_len
2.(283)Move Zeroes
JAVA
class Solution { public void moveZeroes(int[] nums) { int pointer = 0; for (int i = 1; i<nums.length;i++){ if(nums[i]-nums[pointer] == nums[i]){ if(nums[i] != 0){ nums[pointer] = nums[i]; nums[i]=0; pointer++; } }else pointer++; } } }
Python
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
pointer = 0
for i in range(len(nums)):
if(nums[i]-nums[pointer] == nums[i]):
if(nums[i]!=0):
nums[pointer] = nums[i]
nums[i] = 0
pointer +=1
else:
pointer+=1
3.(581)Shortest Unsorted Continuous Subarray
算法:1.先找到排序錯誤子集的起止點和終止點。2.計算該子集內的最大值最小值。3.判斷前部分序列是否有大於子集最小值的部分,後部分序列是否有小於最大值的部分。如果有則修改子序列起始點終點
JAVA
class Solution {
public int findUnsortedSubarray(int[] nums) {
boolean isFirst = true;
int left = 0,right = 0,min = Integer.MAX_VALUE,max=Integer.MIN_VALUE;
for(int i = 0;i<nums.length-1;i++){
if(nums[i+1] < nums[i]){
if(isFirst){
left = i;
right = i+1;
isFirst = false;
}else{
right = i+1;
}
}
}
for (int i = left;i<=right;i++){
min = Math.min(min,nums[i]);
max = Math.max(max,nums[i]);
}
for(int i=0;i <= left;i++){
if(nums[i] > min){
left = i;
}
}
for(int i = nums.length-1 ; i>=right;i--){
if(nums[i]<max){
right = i;
}
}
return right==0?0:right-left+1;
}
}
leetcode第一天