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

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

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

题目的意思是在一个数组中找一段连续的区间,使得这段区间的和的绝对值最小。做法就是利用前缀和,先用一个数组acc[i]来保存从nums[0]到nums[i]的和,同时还要记录下标,所以这里我用pair<int, int>来保存。那么,我们想要得到nums[i]到nums[j]的和,只要用acc[j] - acc[i-1]就可以了。但是这里有一点要注意要加一个辅助的节点,那就是[0, -1],这样就可以确保可以找到以nums[0]开始的区间了。剩下的工作就是对acc数组排序,找到排序后相邻的差的绝对值最小的那一对节点。

1 class Solution { 2 public: 3     /** 4      * @param nums: A list of integers 5      * @return: A list of integers includes the index of the first number  6      *          and the index of the last number 7      */ 8     vector
subarraySumClosest(vector
nums){ 9 // write your code here10 vector
> acc;11 acc.push_back(make_pair(0, -1));12 int sum = 0;13 for (int i = 0; i < nums.size(); ++i) {14 sum += nums[i];15 acc.push_back(make_pair(sum, i));16 }17 sort(acc.begin(), acc.end());18 int min_abs = INT_MAX, a, b, tmp;19 for (int i = 1; i < acc.size(); ++i) {20 tmp = abs(acc[i].first - acc[i-1].first);21 if (min_abs >= tmp) {22 min_abs = tmp;23 a = acc[i-1].second;24 b = acc[i].second;25 }26 }27 vector
res;28 res.push_back(min(a, b) + 1);29 res.push_back(max(a, b));30 return res;31 }32 };

 

转载地址:http://yuael.baihongyu.com/

你可能感兴趣的文章
APK体积优化的一些总结
查看>>
介绍一款Java的方法入参校验工具
查看>>
不借助第三个变量交换 a,b两个值
查看>>
[深入SystemUI]-了解recents的启动流程(一)
查看>>
Android线程池的原理以及项目中实践
查看>>
声明 NSString 类型的属性,到底用 strong 还是 copy ?
查看>>
我的友情链接
查看>>
设置接口跨域调用方法
查看>>
python selenium系列(八)元素定位进阶之分层定位
查看>>
MySQL多表连接优化一例
查看>>
PHP动态扩展模块安装
查看>>
AgileEAS.NET平台开发实例-药店系统-UI层重构技巧及其他
查看>>
Go编程基础 - 类型与变量
查看>>
外链优化的发展
查看>>
用Java实现生产者和消费者的多线程例子
查看>>
alter database datafile offline drop 与 alter tablespace drop datafile 区别 .
查看>>
Java学习课程体系
查看>>
我的友情链接
查看>>
Python install 问题汇总
查看>>
我的友情链接
查看>>