1. 程式人生 > >Leetcode Array 1 twoSum

Leetcode Array 1 twoSum

cnblogs c++ tle leetcode 反轉 pac ber cap 清空

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交換數據

 

Leetcode Array 1 twoSum