思路:
solution1:左闭右闭 则while时要右边的
solution2:左闭右开 则虽然右边界定义为右开的值,但while时不要右边的
代码:
class Solution704_1{
public int seach704_1(int[] nums,int target){
//由于是排序好的,先排除不在这个范围内的
if(target < nums[0] || target > nums[nums.length-1]){
return -1;
}
int left = 0;
int right = nums.length-1;
while(left <= right){
int mid = left + (right-left)/2;
if(nums[mid] == target){
return mid;
}else if (nums[mid] > target){
right = mid-1;
}else if (nums[mid] < target){
left = mid+1;
}
}
return -1;
}
}
class Solution704_2{
public int seach704_2(int[] nums,int target){
//由于是排序好的,先排除不在这个范围内的
if(target < nums[0] || target > nums[nums.length-1]){
return -1;
}
int left = 0;
int right = nums.length;
while(left < right){
int mid = left + (right-left)/2;
if(nums[mid] == target){
return mid;
}else if (nums[mid] > target){
right = mid-1;
}else if (nums[mid] < target){
left = mid+1;
}
}
return -1;
}
}
思路:
solution1:双指针法,快慢指针法--元素相对位置不变
快指针:用来遍历所有元素
慢指针:用来指示非val元素应该待的位置
solution2:双指针法:双向奔赴指针法 -- 元素顺序可以改变
该方法的核心就是永远让我们右手边这位优雅的男士保留一朵非val的玫瑰花
(男士记得不能到走路外面)
等着左边这位女士一步一个脚印的去摘男士的玫瑰花(手里有就不要摘了)
代码:
class Solution27_1 {
public int removeElement1(int[] nums, int val) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
if(nums[fastIndex]!=val){
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
}
class Solution27_2 {
public int removeElement27_2(int[] nums, int val) {
int left = 0;
int right = nums.length-1;
while(right >= 0 &&nums[right]==val){
right --;
}
while(left <= right){
if (nums[left]==val){//女士的手中是val,则需要非val的玫瑰花
nums[left] = nums[right--];//并且男士要向前走一步
}else{
nums[left] = nums[left];//没必要
}
left ++;
//请男士再次保持手里有一朵玫瑰花
while(right >= 0 &&nums[right]==val){
right --;
}
}
return left;
}
}