高频数据结构 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 )

posted @ 2022-07-13 15:44  奋斗中的菲比  阅读(22)  评论(0编辑  收藏  举报