Leetcode:560. Subarray Sum Equals K

最简单的方式,虽然oj没有说超时,但是时间还是挺多的

public class SubArraySum {
    public int subarraySum(int[] nums, int k) {
        int count=0;
        for (int i = 0; i < nums.length; i++) {
            int sum = nums[i];
            if(sum==k){
                count++;
            }
            for (int j = i+1; j < nums.length; j++) {
                sum =sum+nums[j];
                if(sum==k){
                    count++;
                }
            }
        }
        return count;
    }
}

本次的方法是遍历所有起点是最开始元素的子序列,我们起名叫sum[i],只要两个sum[i]的差值是k,则两个i作为起点和终点的子序列就符合要求。由于起点就是最开始元素,只需遍历终点,时间复杂度为O(n)。

 

import java.util.Map;

public class Test2 {
    public int subarraySum(int[] nums, int k) {
        int count=0;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(0, 1);
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum =sum + nums[i];
            count = count+map.getOrDefault(sum-k, 0);    //求SUM[0, i - 1] and SUM[0, j]差值
            map.put(sum,map.getOrDefault(sum,0)+1);
        }
        return count;
    }
}

 

posted on 2017-12-11 20:13  Michael2397  阅读(139)  评论(0编辑  收藏  举报

导航