# 代码随想录打卡day1

### 一，二分法的两种写法

#### 第一种写法

``````class Solution {
public int search(int[] nums, int target) {
//第一种二分法： target 在[left,right]中，开始于[0,len-1], left可与等于right
int left = 0;
int right = nums.length - 1;
int mid = 0;//初始化赋的初值无所谓
while (left <= right) { // left可与等于right
mid = (left+right) / 2;
if (target < nums[mid])
right = mid -1;
else if(nums[mid] < target)
left = mid +1;
else
return mid;
}
return -1;
}
}``````

#### 第二种写法

``````class Solution {
public int search(int[] nums, int target) {
//第二种二分法： target 在[left,right)中，开始于[0,len), left不可等于right
int left = 0;
int right = nums.length;
int mid = 0;//初始化赋的初值无所谓
while (left < right) { //left不可等于right
mid = (left+right) / 2;
if (target < nums[mid])
right = mid;
else if(nums[mid] < target)
left = mid +1;
else
return mid;
}
return -1;
}
}``````

1, right = len / len -1
2, while(left </<= right)
3, right = mid / mid -1

### 二，双指针化简两层循环

``````class Solution {
public int removeElement(int[] nums, int val) {
int j = 0;
for (int i=0; i < nums.length; i++) {
if (nums[i] == val)
continue;
else{
nums[j] = nums[i];
j++;
}
}
return j;
}
}``````

1 声望
0 粉丝
0 条评论