lintcode: Subarray Sum Closest
2016-03-27 18:52
344 查看
Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.
Have you met this question in a real interview?
Yes
Example
Given
return
Challenge
O(nlogn) time
另附参考链接:http://www.cnblogs.com/easonliu/p/4504495.html
Have you met this question in a real interview?
Yes
Example
Given
[-3, 1, 1, -3, 5],
return
[0, 2],
[1, 3],
[1, 1],
[2, 2]or
[0, 4].
Challenge
O(nlogn) time
另附参考链接:http://www.cnblogs.com/easonliu/p/4504495.html
class Solution { public: /** * @param nums: A list of integers * @return: A list of integers includes the index of the first number * and the index of the last number */ vector<int> subarraySumClosest(vector<int> nums){ // write your code here vector<int> retVtr; if (nums.size() == 0) return retVtr; vector<pair<int, int>> auxVtr; auxVtr.push_back(make_pair(0, -1)); int curSum = 0; for (int i=0; i<nums.size(); i++) { curSum += nums[i]; auxVtr.push_back(make_pair(curSum, i)); } sort(auxVtr.begin(), auxVtr.end()); int minDiff = INT_MAX; int minA; int minB; for (int i=1; i<auxVtr.size(); i++) { if (auxVtr[i].first-auxVtr[i-1].first <= minDiff) { minDiff = auxVtr[i].first-auxVtr[i-1].first; minA = auxVtr[i-1].second; minB = auxVtr[i].second; } } retVtr.push_back(min(minA, minB)+1); retVtr.push_back(max(minA, minB)); return retVtr; } };
相关文章推荐
- openstack学习(三)创建虚拟机
- Apache之ab测试工具详解
- Problem P
- 【09类和模块】——3:javascript中java式的类继承
- JavaScript-导航栏点击变色处理
- pb数据窗口一些技取
- codeforces 652C Foe Pairs 水题
- 第四周学习进度条
- 一个三年Android开发的总结-常用的git技巧与误区
- 判断某年某月有几天
- 如何使用VS在SharePont 2013中插入ashx文件
- JVMGC——堆内存的分代
- [面试] C/C++ —— MFC(四)
- 三子棋游戏实现
- 蓝桥杯
- 洗牌
- 一起talk C栗子吧(第一百三十回:C语言实例--C程序内存布局二)
- FFmpeg实现监控摄像头的RTSP协议转RTMP协议直播
- Eclipse 反编译插件JadClipse安装
- java自学历程