代码随想录算法训练营第1天|二分查找、移除元素、有序数组平方
lc704二分查找
思路
注意区间边界,脑中模拟比较情况
代码
class Solution { public int search(int[] nums, int target) { int low = 0, high = nums.length-1; while(low <= high){ int mid = low + (high-low)/2; if (nums[mid] < target){ low = mid + 1; } else if (nums[mid] > target){ high = mid - 1; } else { return mid; } } return -1; } }
lc27移除元素
思路
利用双指针用符合条件的后面元素覆盖前面元素
代码
class Solution { public int removeElement(int[] nums, int val) { int slow = 0, fast = 0; while(fast < nums.length){ if (nums[fast] != val){ nums[slow] = nums[fast]; slow++; fast++; } else { fast++; } } return slow; } }
lc977有序数组平方
思路
注意比较正负数平方后的大小
代码
class Solution { public int[] sortedSquares(int[] nums) { int left = 0, right = nums.length-1, k = nums.length-1; int[] newNums = new int[nums.length]; while (left <= right){ if (nums[left]*nums[left] > nums[right]*nums[right]){ newNums[k--] = nums[left]*nums[left++]; } else { newNums[k--] = nums[right]*nums[right--]; } } return newNums; } }