其他分享
首页 > 其他分享> > Leetcode刷题之矩阵中的指针用法

Leetcode刷题之矩阵中的指针用法

作者:互联网

矩阵中的指针用法

1 快慢指针

​ Leetcode27移除元素

    public int removeElement(int[] nums, int val) {
       int fastIndex=0;
       int slowIndex=0;

       while(fastIndex<nums.length){
           if(nums[fastIndex]!=val){
               nums[slowIndex]=nums[fastIndex];
               slowIndex++;
           }
           fastIndex++;
       }

       return slowIndex;
    }

2 左右指针

​ 二分查找(略)

​ Leetcode209长度最小的子数组

   public int minSubArrayLen(int target, int[] nums) {
        int leftIndex=0;
        int rightIndex=0;
        int size=0;
        int minSize=Integer.MAX_VALUE;
        int sum=0;

        while(rightIndex<nums.length){
            sum+=nums[rightIndex];
            while(sum>=target){
                size=rightIndex-leftIndex+1;
                if(minSize>size){
                    minSize=size;
                }
                sum-=nums[leftIndex];
                leftIndex++;
            }
            rightIndex++;
        }

        return minSize==Integer.MAX_VALUE?0:minSize;
    }

Leetcode581最短无序连续子数组

  public int findUnsortedSubarray(int[] nums) {
        //初始化
        int len = nums.length;
        int min = nums[len - 1];
        int max = nums[0];
        int begin = 0, end = -1;
        //遍历
        for (int i = 0; i < len; i++) {
            if (nums[i] < max) {      //从左到右维持最大值,寻找右边界end
                end = i;
            } else {
                max = nums[i];
            }

            if (nums[len - i - 1] > min) {    //从右到左维持最小值,寻找左边界begin
                begin = len - i - 1;
            } else {
                min = nums[len - i - 1];
            }
        }
        return end - begin + 1;
    }

标签:target,nums,int,矩阵,len,minSize,数组,Leetcode,刷题
来源: https://www.cnblogs.com/fao99/p/16080952.html