【每日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;
    }
}
相关推荐
孤飞7 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
技术专家8 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
csdn_aspnet9 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp9 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
广师大-Wzx10 小时前
一篇文章看懂MySQL数据库(下)
java·开发语言·数据结构·数据库·windows·python·mysql
paeamecium10 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh56311 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮12 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy110112 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先
会编程的土豆12 小时前
01背包与完全背包详解
开发语言·数据结构·c++·算法