LintCode:最接近零的子数组和
2016-01-27 16:54
441 查看
给定一个整数数组,找到一个和最接近于零的子数组。返回第一个和最有一个指数。你的代码应该返回满足要求的子数组的起始位置和结束位置
您在真实的面试中是否遇到过这个题?
Yes
样例
给出[-3, 1, 1, -3, 5],返回[0, 2],[1,
3], [1, 1], [2, 2] 或者 [0,
4]
挑战
O(nlogn)的时间复杂度
标签 Expand
相关题目 Expand
解题思路:
可以先求出位置为i时候的num的0-i数组和sum,在按照大小排序。
排序后将sum相减,输出差最接近0的结果
您在真实的面试中是否遇到过这个题?
Yes
样例
给出[-3, 1, 1, -3, 5],返回[0, 2],[1,
3], [1, 1], [2, 2] 或者 [0,
4]
挑战
O(nlogn)的时间复杂度
标签 Expand
相关题目 Expand
解题思路:
可以先求出位置为i时候的num的0-i数组和sum,在按照大小排序。
排序后将sum相减,输出差最接近0的结果
public class Solution { class Pair { int sum; int index; public Pair(int sum, int index) { super(); this.sum = sum; this.index = index; } } /** * @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 */ public int[] subarraySumClosest(int[] nums) { // write your code here int[] res = new int[2]; if (nums.length == 0 || nums == null) return res; int len = nums.length; if (1 == len) { res[0] = 0; res[1] = 0; return res; } int pre = 0; Pair sumPair[] = new Pair[len + 1]; sumPair[0] = new Pair(0, 0); for (int i = 1; i < len+1; i++) { sumPair[i] = new Pair(pre + nums[i - 1], i); pre = sumPair[i].sum; } Arrays.sort(sumPair, new Comparator<Pair>() { public int compare(Pair a, Pair b) { return a.sum - b.sum; } }); int close = Integer.MAX_VALUE; for (int i = 1; i < len + 1; i++) { if(close>sumPair[i].sum-sumPair[i-1].sum){ close = sumPair[i].sum - sumPair[i-1].sum; int tmp[] = new int[]{sumPair[i].index,sumPair[i-1].index}; Arrays.sort(tmp); res[0] = tmp[0]; res[1] = tmp[1]-1; } } return res; } }
相关文章推荐
- C++的数组、结构体、指针三种复合类型知识点小总结
- IC老化问题
- iGia:smart home security kit
- JQuery插件datatables相关api
- dev 添加等待窗口
- 使用SQLServer Profiler侦测死锁(转)
- js实现上传图片实时预览,兼容chrome IE firefox多浏览器
- 字字珠玑的百度员工离职总结
- Git-仓库状态
- Codeforces Round #272 (Div. 2)AK报告
- 无密码登陆
- Hive的JOIN用法
- 绘制根轨迹_20160126
- android-贪吃蛇开发
- iOS隐藏tableview多余的分割线以及解决cell左边短20px
- Spring注解@Resource和@Autowired区别对比
- 30天30部
- android面试题
- POJ 1330 Nearest Common Ancestors(LCA)
- 关于volley的一些分析-初始化