【每日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;
    }
}
相关推荐
望舒5137 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
独好紫罗兰7 小时前
对python的再认识-基于数据结构进行-a006-元组-拓展
开发语言·数据结构·python
C++ 老炮儿的技术栈7 小时前
Qt 编写 TcpClient 程序 详细步骤
c语言·开发语言·数据库·c++·qt·算法
KYGALYX7 小时前
逻辑回归详解
算法·机器学习·逻辑回归
铉铉这波能秀7 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.7 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
踢足球09297 小时前
寒假打卡:2026-2-8
数据结构·算法
IT猿手7 小时前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人
千逐-沐风7 小时前
SMU-ACM2026冬训周报3rd
算法
老赵说8 小时前
Java基础数据结构全面解析与实战指南:从小白到高手的通关秘籍
数据结构