二分查找:给定一个递增或递减的数组去找其中一个数 思路:不断取中点(left+right)/2 写二分法,区间的定义一般为两种,左闭右闭即[left, right],或者左闭右开即[left, right)。 前者while()条件中left可等于right 后者只能小于right public int search(int[] nums, int target){ int left=0,right=nums.length-1; int index; while (left<=right){ index=(left+right)/2; if (nums[index]==target) return index; if(nums[index]<target){ left=index+1; } else { right=index-1; } } return -1; }
移除元素
1.库函数法:记录除了移除元素以外的元素依次记录,最后从数组头部开始覆盖
public int removeElement1(int[] nums, int val) { int index=0; List<Integer> list=new ArrayList<>(); while (index<=nums.length-1){ if(nums[index]!=val) { list.add(nums[index]); } index++; } for (int i=0;i<list.size();i++){ nums[i]=list.get(i); } return list.size(); } 2.快慢指针法:慢指针指向数组可以覆盖的地方,快指针寻找非移除元素,将非移除元素覆盖到数组前部 public int removeElement2(int[] nums, int val) { int left=0; for(int right=0;right<nums.length;right++){ if(nums[right]!=val){ nums[left]=nums[right]; left++; } } return left;