zoukankan      html  css  js  c++  java
  • 寻找subarray sum的起止index

    思路:用map.put(cur_sum, i); 动不动就break

    一开始设置end = -1是因为没找到

    https://www.geeksforgeeks.org/find-subarray-with-given-sum-in-array-of-integers/

     

    // Java program to print subarray with sum as given sum 
    import java.util.*; 
    
    class GFG { 
    
        public static void subArraySum(int[] arr, int n, int sum) { 
            //cur_sum to keep track of cummulative sum till that point 
            int cur_sum = 0; 
            int start = 0; 
            int end = -1; 
            HashMap<Integer, Integer> hashMap = new HashMap<>(); 
    
            for (int i = 0; i < n; i++) { 
                cur_sum = cur_sum + arr[i]; 
                //check whether cur_sum - sum = 0, if 0 it means 
                //the sub array is starting from index 0- so stop 
                if (cur_sum - sum == 0) { 
                    start = 0; 
                    end = i; 
                    break; 
                } 
                //if hashMap already has the value, means we already 
                // have subarray with the sum - so stop 
                if (hashMap.containsKey(cur_sum - sum)) { 
                    start = hashMap.get(cur_sum - sum) + 1; 
                    end = i; 
                    break; 
                } 
                //if value is not present then add to hashmap 
                hashMap.put(cur_sum, i); 
    
            } 
            // if end is -1 : means we have reached end without the sum 
            if (end == -1) { 
                System.out.println("No subarray with given sum exists"); 
            } else { 
                System.out.println("Sum found between indexes "
                                + start + " to " + end); 
            } 
    
        } 
    
        // Driver code 
        public static void main(String[] args) { 
            int[] arr = {10, 2, -2, -20, 10}; 
            int n = arr.length; 
            int sum = -10; 
            subArraySum(arr, n, sum); 
    
        } 
    } 
    View Code

     

     
  • 相关阅读:
    清北学堂总结(未完待续。。。。。。。)
    洛谷p3372 线段树模版
    SPFA模版
    线段树 洛谷 p1531 I hate it(I hate it too)
    01 背包找装满方案数 洛谷 p1164 小a点菜
    01 找最大剩余体积 洛谷1049 装箱问题
    洛谷 p1880 石子合并 区间dp
    石子合并 最大值
    清北学堂入学测试d
    HTML 标记 3 —— 框架
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13905070.html
Copyright © 2011-2022 走看看