剑指offer面试题之和为S的两个数字
来源:互联网 发布:今年最流行网络歌曲 编辑:程序博客网 时间:2024/04/27 22:45
1,题目:
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
2,想法:
(1),暴力枚举法,需要考虑每一对数,而且需要比较乘积以及记录位置,麻烦!
(2),利用递增排序的思想以及和相等的两个数,离得越远,两数乘积越小。
3,在牛客网上的编码为:
class Solution {public: vector<int> FindNumbersWithSum(vector<int> array,int sum) { //巧妙利用了两端指针,以及和相等的两个数,离得越远,乘机越小的思想 /*if (array.empty()) { return array; } unsigned int i,j; unsigned int length = array.size(); for (i = 0, j = length - 1; i < j;) { if (array[i] + array[j] > sum) { j--; } else if (array[i] + array[j] < sum) { i++; } else { vector<int> temp(2); temp[0] = array[i]; temp[1] = array[j]; return temp; } } vector<int> temp; return temp;*/ //一般的想法是如下暴力枚举 if (array.empty()) { return array; } unsigned int i,j; unsigned int length = array.size(); int multysum = 1000000; int leftlocate = 0, rightlocate = 0; //这个for循环可以改进下 /*for (i = 0; i < length; i++) { for (j = i + 1; j < length; j++) { if (array[i] + array[j] == sum) { if (array[i] * array[j] < multysum) { multysum = array[i] * array[j]; leftlocate = i; rightlocate = j; } } } }*/ for (i = 0; i < length; i++)//那么不需要记录位置和比较大小了,其实就是第一个思路 { for (j = length - 1; j > i; j--) { if (array[i] + array[j] == sum) { vector<int> temp(2); temp[0] = array[i]; temp[1] = array[j]; return temp; } } } vector<int> temp; return temp; /*if (leftlocate != rightlocate) { vector<int> temp(2); temp[0] = array[leftlocate]; temp[1] = array[rightlocate]; return temp; } else { vector<int> temp; return temp; }*/ }};
1 0
- 剑指offer面试题之和为S的两个数字
- 剑指Offer之和为S的两个数字
- 剑指offer(二十一)之和为S的两个数字
- 剑指offer之和为S的两个数字
- 《剑指offer》面试题41 和为S的两个数字
- 剑指Offer:面试题41 和为s的两个数字
- 剑指Offer----面试题41(1):和为s的两个数字
- 剑指offer——面试题41:和为s 的两个数字
- 【剑指offer之和为s的两个数字VS和为s的连续正数序列】
- 剑指offer面试题41和为s的两个数字VS和为s的连续正数序列
- [剑指offer][面试题41]和为s的两个数字 VS 和为s的连续正数序列
- [剑指offer]面试题41:和为s的两个数字,和为s的连续正数序列
- 剑指offer 面试题41 递增数组中和为s的两个数字 | 和为s的连续整数序列
- 剑指offer 面试题41—和为s的两个数字VS和为s的连续正数序列
- 【剑指Offer学习】【面试题41:和为s 的两个数字vs 和为s 的连续正数序列】
- 剑指offer面试题 和为s的两个数字 VS 和为s的连续正数序列
- 剑指offer-面试题41:和为s的两个数字VS和为s的连续正数序列
- 剑指offer之面试题41和为s的两个数字VS和为s的连续正数序列
- 句子摘抄
- ZOJ 2975 Kinds of Fuwas
- Elasticsearch 之 惨痛部署(分片移位)
- pb中数据窗口函数小结(转)
- enable_if
- 剑指offer面试题之和为S的两个数字
- LCS 最大公共序列算法
- Hadoop 基础架构 详解
- c语言细节(一)
- Android官方开发文档Training系列课程中文版:构建第一款安卓应用之环境配置
- 对ajax的理解
- ES6 Generator函数
- Android学习之数据库DBFlow的使用
- nodepad++搭建各种开发环境