LeetCode C++ two sum 兩數之和

今天要練習的 LeetCode 題目是 two sum 兩數之和,並且以 C++ 實作出來。

LeetCode 題目

https://leetcode.com/problems/two-sum/
難度:Easy

two sum 是 LeetCode 題目的第 1 題,
題目是給一個 nums 序列,而且由 nums 序列中的任兩個數字加起來會是 target 這個數字,
題目要求你找出這兩組數字的索引值。

答案

以下為 C++ two sum 的 solution

cpp-two-sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// g++ cpp-two-sum.cpp -o a.out -std=c++11
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i = 0; i < nums.size(); i++) {
for(int j = i+1; j < nums.size(); j++) {
if(nums[i]+nums[j] == target)
return vector<int>({i,j});
}
}
return vector<int>();
}
};

int main() {
vector<int> nums = {2,7,11,15}; int target = 9; // [0,1]
//vector<int> nums = {3,2,4}; int target = 6; // [1,2]
//vector<int> nums = {3,3}; int target = 6; // [0,1]
Solution s;
vector<int> ret = s.twoSum(nums, target);
cout << "[" << ret[0] << "," << ret[1] << "]\n";

return 0;
}

參考
Two Sum - LeetCode
https://leetcode.com/problems/two-sum/
兩數之和 (Two Sum) - 力扣 (LeetCode)
https://leetcode-cn.com/classic/problems/two-sum/description/

其它相關文章推薦
C/C++ 新手入門教學懶人包
LeetCode C++ String to Integer (atoi) 字串轉整數
LeetCode C++ Range Sum Query - Immutable 區域和檢索