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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]. C++:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
for(int i = 0;i < nums.size()-1;i++){
for(int j = i+1;j<nums.size();j++){
if(nums[i]+nums[j] == target){
ans.push_back(i);
ans.push_back(j);
break;
}
}
}
return ans;
}
};

Java:

 public class Solution {
public int[] twoSum(int[] nums, int target) {
int []a = new int[2];
for(int i =0;i<nums.length-1;i++){
for(int j=i+1;j<=nums.length-1;j++){
if(nums[i]+nums[j] == target){
a[0] = i;
a[1] = j;
break;
}
}
}
return a;
}
}

附加一下c++ vector 的简单用法:

1.push_back   在数组的最后添加一个数据
2.pop_back    去掉数组的最后一个数据 
3.at                得到编号位置的数据
4.begin           得到数组头的指针
5.end             得到数组的最后一个单元+1的指针
6.front        得到数组头的引用
7.back            得到数组的最后一个单元的引用
8.max_size     得到vector最大可以是多大
9.capacity       当前vector分配的大小
10.size           当前使用数据的大小
11.resize         改变当前使用数据的大小,如果它比当前使用的大,者填充默认值
12.reserve      改变当前vecotr所分配空间的大小
13.erase         删除指针指向的数据项
14.clear          清空当前的vector
15.rbegin        将vector反转后的开始指针返回(其实就是原来的end-1)
16.rend          将vector反转构的结束指针返回(其实就是原来的begin-1)
17.empty        判断vector是否为空
18.swap         与另一个vector交换数据

 
 

最新文章

  1. 编译可在Nexus5上运行的CyanogenMod13.0 ROM(基于Android6.0)
  2. T-SQL语句简易入门(第一课)
  3. javascript类的类比详解-大白话版
  4. SQL将金额转换为汉子
  5. RecyclerView 结合 CardView 使用(二)
  6. hasLayout与Block formatting contexts的学习(下)
  7. Android开发系列之ListView
  8. A simple stack
  9. Oracle临时表on commit preserver rows和on commit delete rows区别
  10. iOS strong与weak的使用
  11. Spring + Quartz配置实例
  12. java自旋锁
  13. mysql 查找某个表在哪个库
  14. 最小公共祖先 (Tarjan) POJ1470
  15. Redis协议规范(RESP)
  16. mysql 高级
  17. 使用dbms_profiler收集存储过程每步执行时间
  18. 谈谈我对 js原型链的理解
  19. 关于微博api中发布话题的api问题
  20. linux简单安装方法

热门文章

  1. java读取文件的基本操作
  2. 遍历页面所有的Checkbox,显示选中的ID
  3. Console.Write格式化输出
  4. Some lines about EF Code First migration.
  5. unbuntu 矫正电脑系统时间
  6. 各种版本QT下载地址与VS2013+QT5.3.1环境搭建过程(转)
  7. 八、 Java程序初始化的顺序(一)
  8. VMware Workstation/Fusion 中安装 Fedora 23/24 及其他 Linux 系统时使用 Open VM Tools 代替 VMware Tools 增强工具的方法
  9. python的特殊方法总结
  10. Codeforces Round #450 (Div. 2) A. Find Extra One【模拟/判断是否能去掉一个点保证剩下的点在Y轴同侧】