代码随想录DAY1-704二分查找 27移除元素 数组
以前也断断续续刷过一些题,但没有系统记录打卡的习惯,从现在开始吧
这两道题都是关于数组知识的,详细的概念参考了卡哥的介绍:https://programmercarl.com/%E6%95%B0%E7%BB%84%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html#%E6%95%B0%E7%BB%84%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80
704 二分查找
二分查找就是是利用数组的有序性,每轮缩窄一半的查找区间。关键是理解缩窄区间的含义,左闭右闭。时间复杂度 O(logN)。
通过首尾指针,计算数组长度,折半向下取整后比对和target的大小,判断是左还是右。
Java解法
java
.
// An highlighted block
class Solution {
public int search(int[] nums, int target) {
int i = 0, j = nums.length - 1;
while (i <= j) {
int m = (i + j) / 2;
if (nums[m] < target) i = m + 1;
else if (nums[m] > target) j = m - 1;
else return m;
}
return -1;
}
}
Python解法
Python
.
class Solution:
def search(self, nums: List[int], target: int) -> int:
i, j = 0, len(nums) - 1
while i <= j:
m = (i + j) // 2
if nums[m] < target: i = m + 1
elif nums[m] > target: j = m - 1
else: return m
return -1
27 移除元素
该题我的思路是遍历元素,然后和val元素进行对比。主要思路是双指针,java中是快慢指针。
前半段存储不等于val的元素,后半段存储等于val的元素
Java解法
java
.
class Solution {
public int removeElement(int[] nums, int val) {
int n = nums.length;
if (n < 1) {
return n;
}
int slow = 0;
int fast = 0;
while (fast < n) {
if (nums[fast] == val) {
fast++;
continue;
}
nums[slow++] = nums[fast++];
}
return slow;
}
}
另一种解法,遍历元素与val对比,如果当前元素和val相同那么跳过,否则将其放到idx的位置,最终的数组即为答案。
java
.
class Solution {
public int removeElement(int[] nums, int val) {
int idx = 0;
for (int x : nums) {
if (x != val) nums[idx++] = x;
}
return idx;
}
}