代码随想录第一天笔记

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;
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值