704.二分查找
Accept
注意 循环条件 left <= right
class Solution {
public int search(int[] nums, int target) {
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 { // nums[mid] > target
right = mid - 1;
}
}
// 未找到目标值
return -1;
}
}
27.移除元素
Accept
1.快慢指针,经典可for while组合。2.这道 while 可换成if
public class test {
public static void main(String[] args) {
int a[] = {0,1,2,2,3,0,4,2};
Arrays.sort(a);
int slow = 0, fast = 0;
for (; fast < a.length; fast++) {
while (a[slow] != a[fast]){
a[++slow] = a[fast];
}
}
for (int k = 0; k <= slow; k++) System.out.println(a[k]);
}
}