lintcode-medium-Subarray Sum Closest

Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.

 

Example

Given [-3, 1, 1, -3, 5], return [0, 2][1, 3][1, 1][2, 2] or[0, 4].

Challenge

O(nlogn) time

 

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 int[] subarraySumClosest(int[] nums) {
        // write your code here
        
        if(nums == null || nums.length == 0)
            return new int[2];
        
        int[] res = new int[2];
        
        if(nums.length == 1){
            res[0] = 0;
            res[1] = 0;
            return res;
        }
        
        node[] nodes = new node[nums.length];
        int sum = 0;
        
        for(int i = 0; i < nums.length; i++){
            sum += nums[i];
            nodes[i] = new node(i, sum);
        }
        
        Arrays.sort(nodes, new Comparator<node>(){
            public int compare(node n1, node n2){
                return n1.sum - n2.sum;
            }
        });
        
        int index = 0;
        int diff = nodes[index + 1].sum - nodes[index].sum;
        
        for(int i = 0; i < nums.length - 1; i++){
            if(nodes[i + 1].sum - nodes[i].sum < diff){
                index = i;
                diff = nodes[i + 1].sum - nodes[i].sum;
            }
        }
        
        res[0] = Math.min(nodes[index].index, nodes[index + 1].index) + 1;
        res[1] = Math.max(nodes[index].index, nodes[index + 1].index);
        
        return res;
    }
    
    class node{
        int index;
        int sum;
        
        public node(int index, int sum){
            this.index = index;
            this.sum = sum;
        }
    }
    
}

 

posted @ 2016-04-06 12:43  哥布林工程师  阅读(150)  评论(0编辑  收藏  举报