#Leetcode# 1.Two Sum
https://leetcode.com/problems/two-sum/description/
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)$
题解:使用 count ,返回的是被查找元素的个数,如果有,返回 1;否则返回 0;只遍历一个数字,另一个数字提前存起来
代码:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> mp; vector<int> res; int n = nums.size(); for(int i = 0; i < nums.size(); i ++) { mp[nums[i]] = i; } for(int i = 0; i < nums.size(); i ++) { int t = target - nums[i]; if(mp.count(t) && mp[t] != i) { res.push_back(i); res.push_back(mp[t]); break; } } return res; } };
代码(JAVA):
class Solution { public int[] twoSum(int[] nums, int target) { int[] ans = new int[2]; HashMap<Integer, Integer> mp = new HashMap<>(); for(int i = 0; i < nums.length; i ++) { int t = nums[i]; int pos = target - t; if(mp.containsKey(pos)) { ans[0] = Math.min(i, mp.get(pos)); ans[1] = Math.max(i, mp.get(pos)); break; } mp.put(nums[i], i); } return ans; } }
打开新世界的门缝???