Subarray Sum Closest(Medium)

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

不完全对的解法

class Element implements Comparable<Element>{
             int index;
             int value;
             public Element(int i, int v){
                 index = i;
                 value = v;
             }

             public int compareTo(Element other) {
                 return this.value - other.value;
             }

             public int getIndex(){
                 return index;
             }
             public int getValue(){
                 return value;
             }
    }

    public ArrayList<Integer> subarraySum(int[] nums) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (nums==null || nums.length==0) return res;
        int len = nums.length;
        Element[] sums = new Element[len+1];
        sums[0] = new Element(-1,0);
        int sum = 0;
        for (int i=0;i<len;i++){
            sum += nums[i];
            sums[i+1] = new Element(i,sum);
        }
        Arrays.sort(sums);

        int min = Math.abs(sums[0].getValue() - sums[1].getValue());
        int start =  Math.min(sums[0].getIndex(), sums[1].getIndex())+1;
        int end = Math.max(sums[0].getIndex(), sums[1].getIndex());

        for (int i=1;i<nums.length;i++){
            int diff = Math.abs(sums[i].getValue() - sums[i+1].getValue());
            if (diff<min){
                min = diff;
                start = Math.min(sums[i].getIndex(), sums[i+1].getIndex())+1;
                end  = Math.max(sums[i].getIndex(), sums[i+1].getIndex());
            }
        }

        res.add(start);
        res.add(end);
        return res;
    }

Subarray Sum Closest

results matching ""

    No results matching ""