704. 二分查找
题目链接:https://leetcode.cn/problems/binary-search/
1,左闭右闭public int search(int[] nums, int target) { int low=0; int high=nums.length-1; while(low<=high){ int mid = (high+low)/2; if(nums[mid]==target){ return mid; } else if(nums[mid]>target){ high=mid-1; } else{ low=mid+1; } } return -1; }
2. 左闭右开
public int search(int[] nums, int target) { int low=0; int high=nums.length; while(low<high) { int mid = (low + high)/2; if(nums[mid]==target) { return mid; }else if(nums[mid]>target) { high=mid; }else if(nums[mid]<target) { low=mid+1; } } return -1; }
27. 移除元素
题目链接:https://leetcode.cn/problems/remove-element/
暴力的解法:
public static int deleteNum1(int[] arr, int deleteNum) { int size = arr.length; for (int i = 0; i < size; i++) { if (arr[i] == deleteNum) { for (int j = i + 1; j < size; j++) { arr[j - 1] = arr[j]; } i--; size--; } } return size; }
双指针法:
public int removeElement(int[] nums, int i) { int slow = 0; for (int fast = 0; fast < nums.length; fast++) { if (nums[fast] != i) { nums[slow++] = nums[fast]; } } return slow; }
标签:arr,27,nums,int,随想录,mid,fast,移除,size From: https://www.cnblogs.com/hewx/p/18361424