[array] leetCode-1-Two Sum-Easy
2017-11-11 00:10
351 查看
leetCode-1-Two Sum-Easy
descrition
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].
解析
方法 1 : 2 重循环去检查两个数的和是否等于 target。时间复杂度-O(n^2),空间复杂度 O(1)方法 2 : 以空间换时间,使用 hash 表存储已访问过的数,实际上是省去了方法 1 中内层循环的查找时间,时间复杂度 O(n),空间复杂度 O(n)
注意:题目的假设,输入保证有且只有一个解;返回的是下标。
code
#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; class Solution{ public: vector<int> twoSum(vector<int>& nums, int target){ return twoSumByMap(nums, target); } // time-O(n), space-O(n) vector<int> twoSumByMap(vector<int>& nums, int target){ vector<int> ans; unordered_map<int, int> hash; // <num, index> for(int i=0; i<nums.size(); i++){ int another = target - nums[i]; if(hash.find(another) != hash.end()){ // then complexity of unordered_map.find() is // average case: constant // worst case: linear in container size ans.push_back(hash[another]); ans.push_back(i); return ans; } hash[nums[i]] = i; } return ans; } }; int main() { freopen("in.txt", "r", stdin); vector<int> nums; int target; int cur; cin >> target; while(cin >> cur){ nums.push_back(cur); } vector<int> ans = Solution().twoSum(nums, target); if(!ans.empty()) cout << ans[0] << " " << ans[1] << endl; else cout << "no answer" << endl; fclose(stdin); return 0; }
相关文章推荐
- 【leetcode】Array——easy(java)
- LeetCode-Easy刷题(1) Two Sum
- 【Leetcode】【Easy】Remove Duplicates from Sorted Array
- leetcode 1. Two Sum [Easy]
- leetcode.array--1. Two Sum
- LeetCode-Easy部分标签为HashTable 1. Two Sum(一种战胜95%的提交版本的算法)
- leetcode array数组刷题easy组:561:Array Partition I
- [Leetcode 88, Easy] Merge Sorted Array
- leetcode_26_ Remove Duplicates from Sorted Array (easy)
- LeetCode Top Interview Questions Easy Collections 总结一(Array)
- leetcode 697[easy]---Degree of an Array
- 【Leetcode】【Easy】Merge Sorted Array
- Leetcode[Easy] - Two Sum
- LeetCode刷题【Array】 Two Sum
- 【LeetCode】108.Convert Sorted Array to Binary Search Tree(Easy)解题报告
- leetcode 26[easy]--- Remove Duplicates from Sorted Array
- 【leetcode】【Easy】【448. Find All Numbers Disappeared in an Array】【正负位标记】【Array】
- LeetCode 26. Remove Duplicates from Sorted Array——python(easy)
- 【Leetcode-easy-448】Find All Numbers Disappeared in an Array
- [array] leetcode - 53. Maximum Subarray - Easy