博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LintCode-Subarray Sum Closest
阅读量:4659 次
发布时间:2019-06-09

本文共 1448 字,大约阅读时间需要 4 分钟。

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
{ 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 integers25 * @return: A list of integers includes the index of the first number26 * and the index of the last number27 */28 public ArrayList
subarraySumClosest(int[] nums) {29 ArrayList
res = new ArrayList
();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

 

转载于:https://www.cnblogs.com/lishiblog/p/4187961.html

你可能感兴趣的文章
转I/O多路复用之select
查看>>
理解 YOLO
查看>>
检查Linux文件变更Shell脚本
查看>>
ActiveMQ中JMS的可靠性机制
查看>>
oracle操作字符串:拼接、替换、截取、查找
查看>>
”语义“的理解
查看>>
210. Course Schedule II
查看>>
月薪3000与月薪30000的文案区别
查看>>
使用spring dynamic modules的理由
查看>>
Leetcode 117 Populating Next Right Pointers in Each Node 2
查看>>
C++ Primer 第四版中文版
查看>>
变量关系
查看>>
android Service中启动Dialog
查看>>
文件下载之ServletOutputStream
查看>>
linux文件的隐藏属性:chattr
查看>>
【原版的】PHP技术成长规划过程中猿人
查看>>
NTP工作机制及时间同步的方法
查看>>
近段时间学习html和CSS的一些细碎总结
查看>>
学习Coding-iOS开源项目日志(一)
查看>>
第三章 栈和队列
查看>>