努力刷题 day1
1.LeetCode 704. 二分查找【传送门】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int search(int[] nums, int target) { // 避免当 target 小于nums[0] nums[nums.length - 1]时多次循环运算 if (target < nums[0] || target > nums[nums.length - 1]) { return -1; } int left = 0, right = nums.length - 1; while (left <= right) { int mid = left + ((right - left) >> 1); if (nums[mid] == target) return mid; else if (nums[mid] < target) left = mid + 1; else if (nums[mid] > target) right = mid - 1; } return -1; } }
|
1.LeetCode 27. 移除元素【传送门】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { 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;
} }
|