zoukankan      html  css  js  c++  java
  • LintCode-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

    Analysis:

    s[i] = nums[0]+....nums[i], also record the index i into s[i]. Sort array s, and the minimum difference between two consecutive element, is the the subarray.

    Solution:

     1 class Element implements Comparable<Element>{
     2     int val;
     3     int index;
     4     public Element(int v, int i){
     5         val = v;
     6         index = i;
     7     }
     8 
     9     public int compareTo(Element other){
    10         return this.val - other.val;
    11     }
    12 
    13     public int getIndex(){
    14         return index;
    15     }
    16 
    17     public int getValue(){
    18         return val;
    19     }
    20 }
    21 
    22 public class Solution {
    23     /**
    24      * @param nums: A list of integers
    25      * @return: A list of integers includes the index of the first number
    26      *          and the index of the last number
    27      */
    28     public ArrayList<Integer> subarraySumClosest(int[] nums) {
    29         ArrayList<Integer> res = new ArrayList<Integer>();
    30         if (nums.length==0) return res;
    31 
    32         Element[] sums = new Element[nums.length+1];
    33         sums[0] = new Element(0,-1);
    34         int sum = 0;
    35         for (int i=0;i<nums.length;i++){
    36             sum += nums[i];
    37             sums[i+1] = new Element(sum,i);
    38         }
    39 
    40         Arrays.sort(sums);
    41         int min = Math.abs(sums[0].getValue() - sums[1].getValue());
    42         int start =  Math.min(sums[0].getIndex(), sums[1].getIndex())+1;
    43         int end = Math.max(sums[0].getIndex(), sums[1].getIndex());
    44         for (int i=1;i<nums.length;i++){
    45             int diff = Math.abs(sums[i].getValue() - sums[i+1].getValue());
    46             if (diff<min){
    47                 min = diff;
    48                 start = Math.min(sums[i].getIndex(), sums[i+1].getIndex())+1;
    49                 end  = Math.max(sums[i].getIndex(), sums[i+1].getIndex());
    50             }
    51         }
    52 
    53         res.add(start);
    54         res.add(end);
    55         return res;
    56     }
    57 }
  • 相关阅读:
    Flume
    nodejs中npm工具自身升级
    Nodejs v4.x.0API文档学习(1)简介
    nodejs设置NODE_ENV环境变量(1)
    nodejs使用express4框架默认app.js配置说明
    mongodb2.X添加权限
    javascript中new Date浏览器兼容性处理
    Android Studio中文组(中文社区)
    Javascript日期处理类库Moment.js
    android 按两次返回键退出应用
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4187961.html
Copyright © 2011-2022 走看看