• 高频数据结构 hashmap && heap


    Approach 4: Using Hashmap
    Algorithm

    The idea behind this approach is as follows: If the cumulative sum(represented by sum[i]sum[i] for sum up to i^{th}i
    th
    index) up to two indices is the same, the sum of the elements lying in between those indices is zero. Extending the same thought further, if the cumulative sum up to two indices, say ii and jj is at a difference of kk i.e. if sum[i] - sum[j] = ksum[i]−sum[j]=k, the sum of elements lying between indices ii and jj is kk.

    Based on these thoughts, we make use of a hashmap mapmap which is used to store the cumulative sum up to all the indices possible along with the number of times the same sum occurs. We store the data in the form:
    We traverse over the array numsnums and keep on finding the cumulative sum. Every time we encounter a new sum, we make a new entry in the hashmap corresponding to that sum. If the same sum occurs again, we increment the count corresponding to that sum in the hashmap. Further, for every sum encountered, we also determine the number of times the sum sum-ksum−k has occurred already, since it will determine the number of times a subarray with sum kk has occurred up to the current index. We increment the countcount by the same amount.

    After the complete array has been traversed, the countcount gives the required result.
    ``

    public class Solution {
    	/**
    	 * @param nums: A list of integers
    	 * @return: A list of integers includes the index of the first number and the index of the last number
    	 */
    	public List<Integer> subarraySum(int[] nums) {
    		// write your code here
    		List<Integer> result = new ArrayList<>();
    		HashMap<Integer,Integer> map = new HashMap<>();
    		map.put(0, -1);
    		if(nums.length == 0 || nums == null){
    			return null;
    		}
    
    		int currentSum = 0;
    		for (int i = 0; i < nums.length; i++) { 
    			currentSum += nums[i];
    			if(map.containsKey(currentSum)){
    				result.add(map.get(currentSum)+1);
    				result.add(i);
    				return result;
    
    			}
    			map.put(currentSum, i);
    
    
    		}
    		return result;
    	}
    

    }
    ``

    this is a quite interseting question,when i consider it using the calculus idea。
    you can think it as like if k inside between nums[i]~numsj.
    then sum - k must be in the front of the hashmap(cuase the key are the cumulative sum )

  • 相关阅读:
    Window7下安装openssl完整版(亲测实现)
    Android 使用OkHttp
    Android应用中使用AsyncHttpClient来异步网络数据
    Android开发okhttp,retrofit,android-async-http,volley?
    Android开源框架AsyncHttpClient (android-async-http)使用
    15 个最好的 Bootstrap 设计工具推荐
    Bootstrap+angularjs+MVC3+分页技术+角色权限验证系统
    PKU 1509 Glass Beads (最小表示法)
    SQL Server 数据库没有有效全部者的三种解决的方法
    javascript小白学习指南0---1
  • 原文地址:https://www.cnblogs.com/ldphoebe/p/16474137.html
Copyright © 2020-2023  润新知