代码随想录day01 | 数组理论基础、Leetcode 704 二分查找、Leetcode 27 移除元素
704 二分查找
左闭右开
//左闭右开
class Solution {
public int search(int[] nums, int target) {
int begin = 0;
int end = nums.length;
int mid = begin + (end - begin) / 2;
System.out.println("mid = " + mid);
while (begin < mid) {
if (nums[mid] > target) {
end = mid;
mid = begin + (end - begin) / 2;
} else if (nums[mid] < target) {
begin = mid;
mid = begin + (end - begin) / 2;
} else {
return mid;
}
System.out.println("begin = " + begin);
System.out.println("mid = " + mid);
System.out.println("end = " + end);
}
//排除首次begin==end情况
if (nums[mid] == target) {
return mid;
}
return -1;
}
}
左闭右闭
//左闭右闭
class Solution {
public int search(int[] nums, int target) {
int begin = 0;
int end = nums.length - 1;
int mid = begin + (end - begin) / 2;
//此时右边界end-1
while (begin < end - 1) {
if (nums[mid] > target) {
end = mid;
mid = begin + (end - begin) / 2;
} else if (nums[mid] < target) {
begin = mid;
mid = begin + (end - begin) / 2;
} else {
return mid;
}
System.out.println("begin = " + begin);
System.out.println("mid = " + mid);
System.out.println("end = " + end);
}
if (nums[begin] == target) {
return begin;
} else if (nums[end] == target) {
return end;
}
return -1;
}
}
27 移除元素
// 27. 移除元素
//双指针
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int j = nums.length - 1;
for (; i <= j; i++) {
while (nums[i] == val) {
swap(nums, i, j);
j--;
//分两种情况讨论当前值nums[i]是否为val
if (i >= j) {
if (nums[i] == val) {
return i;
} else {
// nums = Arrays.copyOf(nums, i + 1);
return i + 1;
}
}
}
}
// nums = Arrays.copyOf(nums, i + 1);
return i;
}
public void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}