lintcode-medium-Subarray Sum Closest

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
        }
    }
    
}

 

以上是关于lintcode-medium-Subarray Sum Closest的主要内容,如果未能解决你的问题,请参考以下文章