【每日likou】704. 二分查找 27. 移除元素 977.有序数组的平方

  1. 二分查找
    这是一道一看就会,一做就废的题目。
    本题关键:确定target属于左闭右闭区间,还是左闭右开区间。
    思路:
    (1)假设target在左闭右闭区间
    循环条件应该为 left <= right,如果不写等于号,就排查不到num[left]=num[right]=target的情况。
    确定好区间后,right = mid -1.
    (2)假设target在左闭右开区间
    循环条件应该为 left < right,我们定义的是target在[left, right),如果left = right 时,不符合定义了
    确定好区间后,right = mid.
复制代码
class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int centerIndex;
        while(left <= right){
            centerIndex = (right + left) / 2;
            if(nums[centerIndex] == target){
                return centerIndex;
            }else if(nums[centerIndex] > target){
                right = centerIndex - 1;
            }else{
                left = centerIndex + 1;
            }
        }
        return -1;
    }
}
  1. 移除元素

    class Solution {
    public int removeElement(int[] nums, int val) {
    int i = 0;
    int j = nums.length - 1;
    while(i <= j){
    if(nums[i] != val){
    i++;
    }else if(nums[i] == val && nums[j] != val){
    nums[i] = nums[j];
    i++; j--;
    }else if(nums[i] == val && nums[j] == val){
    j--;
    }
    }
    return i;
    }
    }

977.有序数组的平方

本题关键;

平方最大的数要么在数组的第一个位置,要么在数组的最后一个位置。由此想到双指针法。

复制代码
class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] res = new int[nums.length];
        int left = 0;
        int right = nums.length - 1;
        int cur = nums.length - 1;

        while(left <= right){
            if(Math.abs(nums[left])  <= Math.abs(nums[right])){
                res[cur--] = nums[right] * nums[right];
                right--;
            }else if(Math.abs(nums[left])  > Math.abs(nums[right])){
                res[cur--] = nums[left] * nums[left];
                left++;
            }
        }
        return res;
    }
}
相关推荐
Doro再努力25 分钟前
【数据结构08】队列实现及练习
数据结构·算法
清铎2 小时前
leetcode_day12_滑动窗口_《绝境求生》
python·算法·leetcode·动态规划
linweidong2 小时前
嵌入式电机:如何在低速和高负载状态下保持FOC(Field-Oriented Control)算法的电流控制稳定?
stm32·单片机·算法
踩坑记录2 小时前
leetcode hot100 42 接雨水 hard 双指针
leetcode
net3m332 小时前
单片机屏幕多级菜单系统之当前屏幕号+屏幕菜单当前深度 机制
c语言·c++·算法
mmz12072 小时前
二分查找(c++)
开发语言·c++·算法
Insight2 小时前
拒绝手动 Copy!一文吃透 PyTorch/NumPy 中的广播机制 (Broadcasting)
算法
CoovallyAIHub3 小时前
工业视觉检测:多模态大模型的诱惑
深度学习·算法·计算机视觉
Jayden_Ruan3 小时前
C++分解质因数
数据结构·c++·算法
bubiyoushang8883 小时前
MATLAB实现雷达恒虚警检测
数据结构·算法·matlab