1、二分法 leetcode704
左闭右闭写法 [left, right]
注意边界处理
时间复杂度:O(log n)
空间复杂度:O(1)
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right){
int middle = (left + right) / 2;
if(nums[middle] < target){
left = middle + 1;
} else if(nums[middle] > target){
right = middle - 1;
} else {
return middle;
}
}
return -1;
}
}
左闭右开写法 [left, right)
while(left < right){
}
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length;
while(left < right){
int middle = (left + right) / 2;
if(nums[middle] < target){
left = middle + 1;
} else if(nums[middle] > target){
right = middle;
} else {
return middle;
}
}
return -1;
}
}
2.移除元素 leetcode27
暴力解法,注意第9行的 i--
时间复杂度:O(n)
空间复杂度:O(1)
class Solution {
public int removeElement(int[] nums, int val) {
int ans = nums.length;
for(int i = 0; i < nums.length; i++){
if(nums[i] == val){
for(int j = i; j < nums.length - 1; j++){
nums[j] = nums[j + 1];
}
i--;//所有元素向前移动一位,所以i--
ans--;
}
}
return ans;
}
}
双指针
class Solution {
public int removeElement(int[] nums, int val) {
int slow = 0;
int fast = 0;
while (fast<nums.length) {
if (nums[fast]!=val) {
nums[slow] = nums[fast];
slow++;;
}
fast++;
}
return slow;
}
}
3.有序数组的平方 leetcode977
时间复杂度: O(n)
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int[] ans = new int[nums.length];
int k = nums.length - 1;
while(left <= right){
if(nums[left] * nums[left] < nums[right] * nums[right]){
ans[k--] = nums[right] * nums[right];
right--;
}else if(nums[left] * nums[left] >= nums[right] * nums[right]){
ans[k--] = nums[left] * nums[left];
left++;
}
}
return ans;
}
}