Leetcode Array 1 twoSum

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:

 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         int []a = new int[2];
 4         for(int i =0;i<nums.length-1;i++){
 5             for(int j=i+1;j<=nums.length-1;j++){
 6                 if(nums[i]+nums[j] == target){
 7                     a[0] = i;
 8                     a[1] = j;
 9                     break;
10                 }
11             }
12         }
13         return a;
14     }
15 }

附加一下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交换数据

 
posted @ 2017-07-24 00:09  mstark  阅读(236)  评论(0编辑  收藏  举报