classSolution{publicintsearch(int[] nums,int target){// 先判断target是否在nums范围内[有序数组]if(target < nums[0]|| target > nums[nums.length -1]){return-1;}int left =0, right = nums.length -1;while(left <= right){int mid = left +((right - left)>>1);if(nums[mid]> target){
right = mid -1;}elseif(nums[mid]< target){
left = mid +1;}else{return mid;}}return-1;}}
funcsearch(nums []int, target int)int{
right :=len(nums)-1
left :=0for left <= right {
mid := left +(right - left)/2if nums[mid]> target {
right = mid -1}elseif nums[mid]< target {
left = mid +1}else{return mid;}}return-1;}
数组双指针法
classSolution{publicintremoveElement(int[] nums,int val){// 快慢指针int fast =0;int slow;for(slow =0; fast < nums.length; fast++){if(nums[fast]!= val){
nums[slow]= nums[fast];// 这句很关键
slow++;}}return slow;}}
funcremoveElement(nums []int, val int)int{
length:=len(nums)
res:=0for i:=0;i<length;i++{if nums[i]!=val {
nums[res]=nums[i]
res++}}return res
}
publicintminSubArrayLen(int target,int[] nums){int result = Integer.MAX_VALUE;int sum =0;int start =0;int len =0;for(int j =0; j < nums.length; j ++){
sum += nums[j];// 累积到满足条件的窗口时,尝试缩短窗口// 不满足条件,记住当前满足条件的长度,向前继续移动窗口while(sum >= target){
len = j - start +1;
result = result < len ? result : len;// 缩短窗口后的sum
sum -= nums[start ++];}}return result == Integer.MAX_VALUE ?0: result;}
funcminSubArrayLen(target int, nums []int)int{var(
start int
sum int
length int
result =len(nums)+1)for end :=0; end <len(nums); end ++{
sum += nums[end]for sum >= target {
length = end - start +1if result > length {
result = length
}
sum -= nums[start]
start ++}}if result ==len(nums)+1{return0}return result
}