代码随想录算法训练营39期day01 | 704. 二分查找,27. 移除元素
704. 二分查找
写过很多次了,没什么问题,注意点在while(i<=j)这里不能漏掉等于这个条件
class Solution {
public int search(int[] nums, int target) {
int i=0,j=nums.length-1;
int min=0;
while(i <= j) {
min = (i+j)/2;
if(nums[min] == target) {
return min;
}
else if(nums[min] > target) {
j = min-1;
} else {
i = min+1;
}
}
return -1;
}
}
27. 移除元素
思路1:第一遍遍历数组,统计出值为val的元素总数,并且让该项为0 :nums[i]-val。第二次遍历数组,把0排到后面(卡住了,这一步不会写)
int k = 0;
for(int i=0; i<nums.length; i++) {
if(nums[i] == val) {
nums[i] = 0;
k++;
}
}
思路2:双指针,i从0开始,j从nums.length-1开始。 在i<j的条件下,找到第一个值为val的下标i,找到第一个值不为val的下表j,交换。 当i>j(这里i不可能等于j),那么从i开始往右所有都是值为val的元素,k=nums.length-1-i+1,同时全部置0。写错了……
public int removeElement(int[] nums, int val) {
int i = 0, j = nums.length - 1;
int k = 0;
while(true) {
while(i<nums.length && nums[i]!=val) i++;
while(j>0 && nums[j]==val) j--;
if(i>j) {
k = nums.length-i;
while(k<=nums.length-1) nums[k++]=0;
return k;
} else {
// i < j
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
正确思路
移除元素本质:数组元素的删除是后面的元素整体前移的操作
因此
① 暴力法:用两个for循环实现,当匹配到一个元素等于val时,后面的元素整体前移。
② 双指针法:慢指针指向需要覆盖的元素,快指针指向用于覆盖的元素。
为什么我想到双指针法时,只能想到一头一尾,不能想到一快一慢呢?
java 数组相关语法复习
从下标i到最后一个元素,总共有几个:nums.length-1 - i + 1
题目英文学习
704. Binary Search
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
给定一个
n个元素有序的(升序)整型数组nums和一个目标值target,写一个函数搜索nums中的target,如果目标值存在返回下标,否则返回-1。
27. Remove Element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
- Change the array
numssuch that the firstkelements ofnumscontain the elements which are not equal toval. The remaining elements ofnumsare not important as well as the size ofnums. - Return
k.
给你一个数组
nums和一个值val,你需要 [原地] 移除所有数值等于val的元素。元素的顺序可能发生改变。然后返回nums中与val不同的元素的数量。 假设nums中不等于val的元素数量为k,要通过此题, 您需要执行以下操作:
更改
nums数组,使nums的前k个元素包含不等于val的元素。nums的其余元素和nums的大小并不重要。 返回k。