代码随想录刷题 day1 二分查找法+移除元素

704. 二分查找

题目建议: 大家能把 704 掌握就可以,35.搜索插入位置 和 34. 在排序数组中查找元素的第一个和最后一个位置 ,如果有时间就去看一下,没时间可以先不看,二刷的时候在看。

先把 704写熟练,要熟悉 根据 左闭右开,左闭右闭 两种区间规则 写出来的二分法

题目链接: https://leetcode.cn/problems/binary-search/

文章讲解: https://programmercarl.com/0704.%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE.html

视频讲解: https://www.bilibili.com/video/BV1fA4y1o715

class Solution {
    public int search(int[] nums, int target) {
        if(nums==null||nums.length==0){
            return -1;
        }
        int left = 0;
        int right = nums.length-1;
        int mid = -1;
        while (left<=right){
            mid = left+(right-left)/2;
            if(nums[mid]==target){
                return mid;
            }else if(nums[mid]>target){
                right = mid - 1;
            }else{
                left = mid+1;
            }
        }
        return -1;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.


27. 移除元素

题目建议: 暴力的解法,可以锻炼一下我们的代码实现能力,建议先把暴力写法写一遍。 双指针法 是本题的精髓,今日需要掌握,至于拓展题目可以先不看。

题目链接: https://leetcode.cn/problems/remove-element/

文章讲解: https://programmercarl.com/0027.%E7%A7%BB%E9%99%A4%E5%85%83%E7%B4%A0.html

视频讲解: https://www.bilibili.com/video/BV12A4y1Z7LP

public int removeElement(int[] nums, int val) {
        if(nums==null||nums.length==0){
            return 0;
        }
        int left = 0;
        int right = nums.length-1;
        while(left<=right){
            if(nums[left]!=val){
                left++;
            }else{
                nums[left] = nums[right];
                right--;
            }
        }
        return left; 
    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

时间复杂度分析: O(n) 一次遍历整个数组的元素就完成了所有的操作

空间复杂度分析: O(1) 只定义了局部的变量 没有从新分配和数组一样大的空间

posted @ 2023-07-27 21:38  Appinn  阅读(1)  评论(0编辑  收藏  举报  来源