Input: A seq of int <3, 4, 1, 2> A target int 5 Output: whether a continuous subseq sums up to the target target 5 -> True. more info on 1point3acres target 4 -> True target 6 -> False follow up: 分析时间复杂度,空间复杂度,改成输出最短长度的subsequence的长度,以及 有什么test case // get the prefix sum // save the prefix sum to a hashset // every time we get a target, we check for each number x in the // hashset, if tartget + k exists // in the case of two prefix with same val, use two hashset. save the second to dup set public boolean subarraySum(int[] array, int target){ HashSet<Integer> set = new HashSet<>(); HashSet<Integer> dup = new HashSet<>(); // get the prefix int prev = array[0]; for(int i = 1; i < array.length; i++){ int curSum = array[i] + prev; prev = curSum; if(!set.contains(curSum)){ set.add(curSum); }else{ dup.add(curSum); } } return check(set, dup, target); } private boolean check(HashSet<Integer> set, HashSet<Integer> dup, int target){ for(int num : set){ int numToCheck = num + target; if(num != numToCheck && set.contains(numToCheck )){ return true; }else if(num == numToCheck && dup.contains(numToCheck)){ return true; } } return false; } // 改成输出最短长度的subsequence的长度,以及 // 有什么test case public int subarraySum(int[] array, int target){ HashMap<Integer, List<Integer>> prefix = new HashMap<>(); // get the prefix int prev = array[0]; for(int i = 0; i < array.length; i++){ int curSum = array[i] + prev; prev = curSum; List<Integer> list = prefix.get(curSum); if(list == null){ map.put(curSum, new ArrayList<>()); } list.add(i); } // consertive way of doing this // if(!map.contains(curSum)){ // map.put(curSum, new ArrayList<>()); // } // map.put(curSum, map.get(curSum).add(i)); return check(prefix, target); } private int check(HashMap<Integer, List<Integer>> prefix, int target)){ for(int num : prefix.keySet()){ int sum = target + num; // two cases: // sum is not equal to the num // check if the sum exists in the hashmap if(sum != num && prefix.containsKey(sum)) return prefix.get(sum)[0] - prefix.get(num)[0]; // sum is equal to the num // check if the size of rhe list > 1 if(sum == num && prefix.get(num).size() > 1) return prefix.get(sum)[1] - prefix.get(sum)[0]; } return -1; }
whether a subarray sums up to the target
猜你喜欢
转载自www.cnblogs.com/tobeabetterpig/p/9550506.html
今日推荐
周排行