Leetcode - Minimum Size Subarray Sum

My code:

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        int head = 0;
        int end = 0;
        int sum = 0;
        boolean isForward = true;
        int minLen = Integer.MAX_VALUE;
        while (end < nums.length) {
            if (isForward) {
                sum += nums[end];
                if (sum >= s) {
                    minLen = Math.min(minLen, end - head + 1);
                    isForward = false;
                }
                else {
                    isForward = true;
                    end++;
                }
            }
            else {
                sum = sum - nums[head];
                head++;
                if (sum >= s) {
                    minLen = Math.min(minLen, end - head + 1);
                    isForward = false;
                }
                else {
                    isForward = true;
                    end++;
                }
            }
        }
        return minLen < Integer.MAX_VALUE ? minLen : 0;
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        int[] a = {2,3,1,2,4,3};
        System.out.println(test.minSubArrayLen(7, a));
    }
}

我自己的做法就是 sliding window, O(n)
比较简单。但是还有一种 O n log n 的做法。
我没怎么搞懂。
博文放在这里,有机会再研究。
https://leetcode.com/discuss/35378/solutions-java-with-time-complexity-nlogn-with-explanation

**
总结:
sliding window
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        int min = Integer.MAX_VALUE;
        int begin = 0;
        int end = 0;
        int sum = 0;
        while (begin <= end && end < nums.length) {
            sum += nums[end];
            if (sum >= s) {
                min = Math.min(min, end - begin + 1);
                sum -= nums[begin];
                sum -= nums[end];
                begin++;
            }
            else {
                end++;
            }
        }
        if (min == Integer.MAX_VALUE)
            return 0;
        else
            return min;
    }
}

这道题木的思路就是 sliding window,但是奇怪的是,为什么时间复杂度是 O(n) 呢?

programcreek 上面对这道题木的解释很直接简洁:

We can use 2 points to mark the left and right boundaries of the sliding window. When the sum is greater than the target, shift the left pointer; when the sum is less than the target, shift the right pointer.

参考网址:
http://www.programcreek.com/2014/05/leetcode-minimum-size-subarray-sum-java/

当然,这道题目还有一种 nlogn的解法,
就是以一侧为开头,比如nums[i],新开一个数组一次记录元素的和。
然后每次用binary search 找最接近target + sum[i]的index,然后求出长度。具体看之前的网页链接。

Anyway, Good luck, Richardo!

你可能感兴趣的:(Leetcode - Minimum Size Subarray Sum)