[leetcode 1] Two Sum
2016-03-15 22:25
357 查看
Question:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
分析:
暴力法很简单,二重循环,但是超时了;
可以声明一个辅助数组,是对原数组的拷贝,这样,可以将辅助数组进行排序,排序后通过左右两个索引指针就可以判断是哪两个值相加为target;
然后在原数组中找到这两个值所对应的下标。
代码如下:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
分析:
暴力法很简单,二重循环,但是超时了;
可以声明一个辅助数组,是对原数组的拷贝,这样,可以将辅助数组进行排序,排序后通过左右两个索引指针就可以判断是哪两个值相加为target;
然后在原数组中找到这两个值所对应的下标。
代码如下:
<span style="background-color: rgb(255, 255, 255);"><span style="font-size:14px;">class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res(2); vector<int> cp(nums); sort(nums.begin(),nums.end()); int left = 0; int right = nums.size()-1; while(left < right){ int sum = nums[left] + nums[right]; if(sum < target) ++left; else if(sum > target) --right; else{ break; } } for(int i = 0; i < nums.size(); ++i){ if(cp[i] == nums[left]){ left = i; break; } } for(int i = 0; i < nums.size(); ++i){ if(cp[i] == nums[right] && i != left){ right = i; break; } } res[0] = min(left,right); res[1] = max(left,right); return res; //暴力法 /* for(int i = 0; i < nums.size()-1; ++i){ for(int j = i+1; j < nums.size(); ++j){ if(nums[i] + nums[j] == target){ res.push_back(i); res.push_back(j); break; } } } return res;*/ } };</span></span>
相关文章推荐
- iOS 夜间模式
- 网站图片优化-解码JPEG
- Android课程---Oracle VM VirtualBox出现不能为虚拟机打开一个新任务
- [转]TOMCAT原理以及处理HTTP请求的过程、ContextPath ServletPath
- 自动生成四则运算题目
- 读取Resources和Assets中的文件
- 多线程环境下安全使用集合 API
- Android ADT开发环境配置代码自动提示功能
- 轻量级jQuery带底栏轮播(焦点图)插件slideBox
- 十个开源库分享(一)
- linux基础命令(2)
- 集体智慧编程——K近邻分类器预测价格
- 分布式web架构演进
- C++中的基类与派生类
- JS基础回顾,小练习(Event事件)
- 数据结构--线性表复习
- MySQL读写分离
- 权限管理系统文档梳理
- coreboot学习4:启动流程跟踪之romstage阶段
- POJ-2051