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 }
  • 相关阅读:
    Yii框架(一)
    phpStorm中使用xdebug断点调试php代码
    在mysql存储过程中拼接sql解决in的字段类型不匹配问题
    openjdk源码阅读导航
    深入理解tomcat9---源码构建
    API权限控制与安全管理
    java虚拟机性能监控调优及原则
    java十年技术栈[总结复习用]
    spring boot配置文件application.propertis
    php危险的函数和类 disable_functions/class
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4187961.html
Copyright © 2011-2022 走看看