package SecondBrush.Array; /** * 704. 二分查找 */ public class BinarySearch_704 { public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = (left + right) / 2; if (target == nums[mid]) { return mid; } else if (target > nums[mid]) { left = mid + 1; } else { right = mid - 1; } } return -1; } }
package SecondBrush.Array; /** * 27. 移除元素 * 快慢指针 * 这里可以使用暴力O(n^2),可以使用双指针 O(n) * */ public class RemoveElement_27 { public int remove_v(int []nums,int target){ int len = nums.length; for (int i = 0; i < nums.length; i++) { if (nums[i] == target){ for (int j = i+1; j < nums.length; j++) { nums[j-1] = nums[j]; len--; i--; } } } return len; } public int remove(int [] nums,int val){ int slow = 0; for (int fast = 0; fast < nums.length; fast++) { if (nums[fast] != val){ nums[slow] = nums[fast]; slow++; } } return slow; } }