• Subarray Sum Closest


    Question

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

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

    Answer

    这道题延续Subarray Sum的思路,即将[0, i]的sum存起来。这里构造了一个新的类,Pair。一方面存sum值,一方面存index。然后根据sum值排序,算相邻sum值的差值。差值最小的即为结果。时间复杂度是O(nlogn),空间复杂度是O(n)。

    注意:假设[0-2]和[0-4]的sum值的差值最小,那么结果为index[3,4]

     1 public class Solution {
     2     
     3     class Pair {
     4         public int sum;
     5         public int index;
     6         public Pair(int sum, int index) {
     7             this.sum = sum;
     8             this.index = index;
     9         }
    10     }
    11     /**
    12      * @param nums: A list of integers
    13      * @return: A list of integers includes the index of the first number 
    14      *          and the index of the last number
    15      */
    16     public int[] subarraySumClosest(int[] nums) {
    17         // write your code here
    18         int[] result = new int[2];
    19         if (nums == null || nums.length == 0) {
    20             return result;
    21         }
    22         int len = nums.length;
    23         int sum = 0;
    24         List<Pair> list = new ArrayList<Pair>();
    25         for (int i = 0; i < len; i++) {
    26             sum += nums[i];
    27             Pair tmp = new Pair(sum, i);
    28             list.add(tmp);
    29         }
    30         Collections.sort(list, new Comparator<Pair>() {
    31             public int compare(Pair a, Pair b) {
    32                 return (a.sum - b.sum);
    33             }
    34         });
    35         int min = Integer.MAX_VALUE;
    36         for (int i = 1; i < len; i++) {
    37             int diff = list.get(i).sum - list.get(i - 1).sum;
    38             if (diff < min) {
    39                 min = diff;
    40                 int index1 = list.get(i).index;
    41                 int index2 = list.get(i - 1).index;
    42                 if (index1 < index2) {
    43                     result[0] = index1 + 1;
    44                     result[1] = index2;
    45                 } else {
    46                     result[0] = index2 + 1;
    47                     result[1] = index1;
    48                 }
    49             }
    50         }
    51         return result;
    52     }
    53 }
  • 相关阅读:
    字典树+二叉树
    ##22
    简单代码优雅写
    全排列
    【持续更新】哟!又在写BUG啊!
    大整数加法和大整数乘法
    【框架编程思想】线数筛的高级应用(欧拉12题和欧拉21题)
    【持续更新】 用算法流程实现的代码块们
    记忆化
    资源收集
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/5995253.html
Copyright © 2020-2023  润新知