1. Two Sum
JAVA
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> m = new HashMap<>(); for (int i = 0;; ++i) { int x = nums[i]; int y = target - x; if (m.containsKey(y)) { return new int[] {m.get(y), i}; } m.put(x, i); } } }
C++
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> m; for (int i = 0;; ++i) { int x = nums[i]; int y = target - x; if (m.count(y)) { return {m[y], i}; } m[x] = i; } } };
JAVASCRIPT
var twoSum = function (nums, target) {
const m = new Map();
for (let i = 0; ; ++i) {
const x = nums[i];
const y = target - x;
if (m.has(y)) {
return [m.get(y), i];
}
m.set(x, i);
}
};
Comments
Post a Comment