数组理论知识
1 数组内存空间的地址是连续的,删除或者增添元素的时候,要移动其他元素
2 数组的元素是不能删除的,只能覆盖
LeetCode704二分查找
题目链接:https://leetcode.cn/problems/binary-search/
写法一:左闭右闭
class Solution {
public static int search(int[] nums, int target) {
int i = 0;
int j = nums.length-1;
while (i <= j){
int index = (i + j) >> 1;
if (nums[index] > target){
j = index - 1;
continue;
}
if (nums[index] < target){
i = index + 1;
continue;
}
if (nums[index] == target ){
return index;
}
}
return -1;
}
}
写法2:左闭右开
class Solution {
public static int search(int[] nums, int target) {
int i = 0;
int j = nums.length-1;
while (i < j){
int index = (i + j) >> 1;
if (nums[index] > target){
j = index;
continue;
}
if (nums[index] < target){
i = index + 1;
continue;
}
if (nums[index] == target ){
return index;
}
}
return -1;
}
}
Leetcode 27 移除元素
题目链接:https://leetcode.cn/problems/remove-element/
暴力破解
时间复杂度:O(n^2)
空间复杂度:O(1)
双指针(快慢指针法)
public class Solution {
public static int removeElement(int[] nums, int val) {
int slow = 0;
for (int fast = 0;fast < nums.length;fast++){
if (nums[fast] != val){
nums[slow++] = nums[fast];
}
}
return slow;
}
}