数组-二分查找-day01

  1. 移除元素
    题目链接https://leetcode.cn/problems/remove-element/submissions/691386333/
    思路:
    本题需要再不解释辅助数组的情况下,将指定的元素覆盖掉;通过快慢指针的方式,将val的值全部覆盖掉;
    class Solution {
    public int removeElement(int[] nums, int val) {
    int snow=0;
    int len=nums.length-1;
    for(int i=0;i<=len;i++){//为了保证能够变量到所有的元素,i<=len
    if(nums[i]!=val){
    nums[snow++]=nums[i];
    }
    }
    return snow;
    }
    }

  2. 二分查找
    题目链接:https://leetcode.cn/problems/binary-search/description/
    思路: 题目是一个升序的数组且val值不重复,因此通过2分查找的方式,去查找元素,最多需要logn次;代码的实现逻辑是左闭右闭,简单点说就是考虑数组的边间;
    class Solution {
    public int search(int[] nums, int target) {
    if (target < nums[0] || target > nums[nums.length - 1]) {
    return -1;
    }
    int left=0,right=nums.length-1; //左闭右闭

    while(left<=right){
    int mid = left + ((right - left) >> 1); //防止越界
    if(nums[mid]<target){
    left=mid+1; //右
    }
    if(nums[mid]>target){
    right=mid-1;//左
    }
    if(nums[mid]==target){
    return mid;
    }
    }
    return -1;
    }
    }

题目:977. 有序数组的平方
代码链接:https://leetcode.cn/problems/squares-of-a-sorted-array/description/
思路:一个升序的数组,数组中可能有负数;通过代码将数组平方后,数组中的元素同样是升序排列;因此借助了一个辅助数组,每次将最大的值,填充到辅助数组的最末尾;
class Solution {
public int[] sortedSquares(int[] nums) {
int l = 0; //开始位置
int r = nums.length - 1; //结束位置
int[] res = new int[nums.length];//辅助数组
int j = nums.length - 1;
while(l <= r){
if(nums[l] * nums[l] > nums[r] * nums[r]){
res[j--] = nums[l] * nums[l++];//因为有负数的存在,所有l位置的值的平方可能大于r位置;l向后移动一位
}else{
res[j--] = nums[r] * nums[r--];//r向前移动一位
}
}
return res;
}
}

posted @ 2026-01-14 21:44  whq001  阅读(7)  评论(0)    收藏  举报