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

  1. 二分查找
    这是一道一看就会,一做就废的题目。
    本题关键:确定target属于左闭右闭区间,还是左闭右开区间。
    思路:
    (1)假设target在左闭右闭区间
    循环条件应该为 left <= right,如果不写等于号,就排查不到numleft=numright=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;
    }
}
相关推荐
从零开始的代码生活_21 分钟前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI1 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅
atunet1 小时前
关于图算法中的连通分量检测与最小割问题7
算法
心运软件1 小时前
银行客户流失预测(Python 完整实战)
算法
邪神与厨二病1 小时前
牛客周赛 Round 153
python·算法
qizayaoshuap3 小时前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
皓月斯语4 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet4 小时前
树状结构在查询优化中的作用与实现细节7
算法
徐凤年_5 小时前
rog_map参数理解
算法
春日见5 小时前
算法与数据结构----哈希表
数据结构·人工智能·算法·机器学习·自动驾驶·哈希算法·散列表