【每日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;
    }
}
相关推荐
不正经学生1 小时前
C语言预处理详解:编译器真正动手之前的那些事
c语言·开发语言·算法·面试·bug
毕竟是shy哥4 小时前
计算YOLO数据集中每个类的目标数
算法·yolo·机器学习
M78佐菲4 小时前
Linux学习笔记:TCP协议
linux·笔记·学习·tcp/ip·算法
圣保罗的大教堂4 小时前
leetcode 1406. 石子游戏 III 困难
leetcode
晊晌_h5 小时前
嵌入式从0到精通——数据结构总结[特殊字符]
数据结构·算法·排序算法
我找到地球的支点啦6 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
罗西的思考6 小时前
【OpenClaw具身硬件】ZeroClaw 源码阅读笔记(3)--- RAG
人工智能·算法·机器学习
浪里镖客7 小时前
位姿转换矩阵写法-个人习惯(计算机理解其实是相反的)
线性代数·算法·矩阵
小白羊丨10 小时前
如何诊断 Prompt 模板导致的效果下降?
人工智能·算法·prompt
OPEN-F11 小时前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法