1.TwoSum
2017-05-13 15:21
92 查看
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].
(给定一个整型数组,返回其中和为指定数值的两个数的下标。
假定输入数组有唯一解,且不能使用同一个数两次。)
找到一个数组中和为指定数值的两个数并不难,遍历数组中的元素即可,实现起来并不难。
解法一:
上述解法的时间复杂度为O(n^2)。
OJ是不会让它过的。
解法二:
上述代码即可Accept。
测试代码:
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].
(给定一个整型数组,返回其中和为指定数值的两个数的下标。
假定输入数组有唯一解,且不能使用同一个数两次。)
找到一个数组中和为指定数值的两个数并不难,遍历数组中的元素即可,实现起来并不难。
解法一:
vector<int> TwoSum::TwoSum1(vector<int>& nums, int target) { vector<int> result; for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++) { if (nums[i] + nums[j] == target) { result.push_back(i); result.push_back(j); return result; } else if (nums[i] + nums[j] > target) { break; } } } return result; }
上述解法的时间复杂度为O(n^2)。
OJ是不会让它过的。
解法二:
#include <unordered_map> vector<int> TwoSum::TwoSum2(vector<int>& nums, int target) { vector<int> result; // 创建一个哈希表 unordered_map<int, int> hash; for (int i = 0; i < nums.size(); i++) { // 遍历时直接查找对应值是否存在哈希表中 int targetNum = target - nums[i]; if (hash.find(targetNum) != hash.end()) { result.push_back(hash[targetNum]); result.push_back(i); return result; } // 哈希表的键值对为:数组中元素的值,该元素的下标值 // 这样在查找到两个数的时候便于返回下标 hash[nums[i]] = i; } return result; }
上述代码即可Accept。
测试代码:
TwoSum twoSum; vector<int> input{ 2, 7, 11, 15 }; vector<int> result = twoSum.TwoSum1(input, 9); //vector<int> result = twoSum.TwoSum2(input, 9); for (vector<int>::iterator it = result.begin(); it != result.end(); ++it) { cout << *it << "\n"; } cout << endl;
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode刷题,没想到这么难搞!
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode #1 Two Sum
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解