剑指offer 和为S的两个数字
2016-03-16 20:56
369 查看
输入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。 [align=left]该算法没有利用数组是有序的这个信息,虽然算法时间也是O(n),但是空间消耗也是O(n)[/align][align=left]
时间消耗O(n),空间消耗O(1)
[/align] |
12345678910111213141516171819202122 | class Solution { public : vector< int > FindNumbersWithSum(vector< int > array, int sum) { int i = 0 ; int j = array.size()- 1 ; vector< int > result; while (i < j) { if (array[i] + array[j] == sum) { result.push_back(array[i]); result.push_back(array[j]); return result; } else if (array[i] + array[j] > sum) j--; else i++; } return result; } }; |
相关文章推荐
- 剑指offer 判断树是不是对称的
- jQuery EasyUI中常常遇到的问题(FAQ)
- js笔记
- 【优化】前端优化的几种常用方法(持续更新)
- 剑指offer之有序二维数组查找
- 在html <table> 标签的中background和bgcolor两个属性有什么关系?
- 滚动监听导航 JQUERY 易懂
- JSP初学
- javascript 关于弹出新页面始终在正中央方法
- CSS中box-reflect特性以及火狐浏览器替代方案
- js调用百度地图API
- JavaScript中的引用类型
- Zox's code life 人生就是不停的战斗! xxx is not in the sudoers file.This incident will be reported.的解决方法
- 剑指offer 数字在排序数组中出现的次数
- 剑指offer 数组中只出现一次的数字
- NodeJS实战
- JavaScript 代码规范
- 剑指offer青蛙跳台阶问题
- 剑指offer 旋转数组
- 细谈CSS布局方式