博文

目前显示的是标签为“Subarray Sum”的博文

Subarray Sum Closest

Problem: Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number. 2/23/2018 update Again well explained below. Solution with better format: 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 */ class Pair { int index; int sum; public Pair ( int index, int sum) { this . index = index; this . sum = sum; } } public int [] subarraySumClosest ( int [] nums) { // write your code here if (nums == null || nums . length == 0 ) return new int []{}; Pair [] pairs = new Pair [nums . length + 1 ]; pairs[ 0 ] = new Pair ( - 1 , 0 ); int sum = 0 ; for ( int i = 0 ; i < nums . length; i ++ ) { sum += nums[i]; pairs[...

Subarray Sum

Problem: Given an integer array, find a subarray where the sum of numbers is  zero . Your code should return the index of the first number and the index of the last number.  Notice There is at least one subarray that it's sum equals to zero. 2/23/2018 update It has been explained pretty well below. But still need to note that, the prefix sum stores in hashtable instead of array. Initial the hashtable with (0, -1) is important. The case[1, -1] would not pass without (0, -1) pushed. Since it can not find the index before 0. Solution: 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 ArrayList< Integer > subarraySum ( int [] nums) { // write your code here ArrayList< Integer > res = new ArrayList<> (); HashMap< Integer , Integer > hm...