27.移除元素:https://leetcode.cn/problems/remove-element/
自己的思路:
暴力解法:使用到了额外的空间,创建一个ArraryList<Integer>集合,再循环遍历数组,找到与val不相同的值,加入进集合中,最后返回集合的长度。
缺点:创建了额外的空间。
算法思路:使用到了快慢双指针,不使用额外的空间,只需要在一个for循环中即可完成元素的移除
以慢指针为准返回移除元素之后的数组长度,主要思想是将fast指针的值赋给slow指针
1.当fast指针不等于val时,nums[slow] = nums[fast] --> slow和fast指针一起++;
2.当fast指针等于val时,fast指针++,slow指针保持不动。
public class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.removeElement(new int[]{3, 2, 2, 3}, 3)); } public int removeElement(int[] nums, int val) { int fastIndex = 0; int slowIndex; for (slowIndex= 0; fastIndex < nums.length; fastIndex++) { if (nums[fastIndex] != val){ nums[slowIndex] = nums[fastIndex]; slowIndex++; } } return slowIndex; } }
双指针算法的优化:此类题目无需考虑数组元素的顺序,所以双指针可以从两头向中间靠近,right从nums.length开始,否则会少计算一个元素
1.当nums[left] == val时,nums[left] = nums[right-1];right向左进;
2.当nums[left] != val时,left向右进;
public class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.removeElement(new int[]{0, 1, 2, 3, 3,0,4,2}, 2)); } public int removeElement(int[] nums, int val) { int left = 0; int right = nums.length; while (left < right){ if (nums[left] == val){ nums[left] = nums[right-1]; right--; }else { left++; } } return left; } }
704.二分查找:https://leetcode.cn/problems/binary-search/
注意点:
1.考虑区间的定义:左闭右闭、左闭右开;(两种区间的left和right的取值也不同)
public class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.search(new int[]{5}, 5)); }
//左闭右闭
public int search(int[] nums, int target) {
int left = 0; int right = nums.length-1; while (left <= right){ //left==right是有意义的 int mid = (left+right)/2; if (target < nums[mid]){ right = mid -1 ; }else if (target > nums[mid]){ left = mid + 1; //+1、-1是因为确认mid不等于target }else if (target == nums[mid]){ return mid; } } return -1; } }
public class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.search(new int[]{5}, 5)); } public int search(int[] nums, int target) { int left = 0; int right = nums.length; while (left < right){ int mid = (left+right)/2; if (target < nums[mid]){ right = mid ; }else if (target > nums[mid]){ left = mid +1; }else if (target == nums[mid]){ return mid; } } return -1; } }