GeezerVison is showing github.com — 1_two_sum · sunshinenny/leetcode-python-java@5a62e42
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: .gitignore +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
2 | 2 | __pycache__/ |
3 | 3 | *.py[cod] |
4 | 4 | *$py.class |
| 5 | +.idea/ |
5 | 6 |
|
6 | 7 | # C extensions |
7 | 8 | *.so |
|
Collapse file
Copy file name to clipboard +13Lines changed: 13 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | + public class Solution { |
| 2 | + public int[] twoSum(int[] nums, int target) { |
| 3 | + Map<Integer, Integer> map = new HashMap<>(); |
| 4 | + for (int i = 0; i < nums.length; i++) { |
| 5 | + int x = nums[i]; |
| 6 | + if (map.containsKey(target - x)) { |
| 7 | + return new int[]{map.get(target - x), i}; |
| 8 | + } |
| 9 | + map.put(x, i); |
| 10 | + } |
| 11 | + throw new IllegalArgumentException("No two sum solution"); |
| 12 | + } |
| 13 | + } |
Collapse file
Copy file name to clipboard +51Lines changed: 51 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +class Solution(object): |
| 2 | + # def twoSum(self, nums, target): |
| 3 | + # """ |
| 4 | + # :type nums: List[int] |
| 5 | + # :type target: int |
| 6 | + # :rtype: List[int] |
| 7 | + # """ |
| 8 | + # #n^2 |
| 9 | + # ls = len(nums) |
| 10 | + # for i in range(ls): |
| 11 | + # for j in range(i + 1, ls): |
| 12 | + # if nums[i] + nums[j] == target: |
| 13 | + # return [i, j] |
| 14 | + |
| 15 | + # def twoSum(self, nums, target): |
| 16 | + # # hash 1 |
| 17 | + # hash_nums = {} |
| 18 | + # for index, num in enumerate(nums): |
| 19 | + # try: |
| 20 | + # hash_nums[num].append(index) |
| 21 | + # except KeyError: |
| 22 | + # hash_nums[num] = [index] |
| 23 | + # for index, num in enumerate(nums): |
| 24 | + # another = target - num |
| 25 | + # try: |
| 26 | + # candicate = hash_nums[another] |
| 27 | + # if another == num: |
| 28 | + # if len(candicate) > 1: |
| 29 | + # return candicate |
| 30 | + # else: |
| 31 | + # continue |
| 32 | + # else: |
| 33 | + # return [index, candicate[0]] |
| 34 | + # except KeyError: |
| 35 | + # pass |
| 36 | + |
| 37 | + def twoSum(self, nums, target): |
| 38 | + # hash 2 |
| 39 | + hash_nums = {} |
| 40 | + for index, num in enumerate(nums): |
| 41 | + another = target - num |
| 42 | + try: |
| 43 | + hash_nums[another] |
| 44 | + return [hash_nums[another], index] |
| 45 | + except KeyError: |
| 46 | + hash_nums[num] = index |
| 47 | + |
| 48 | +if __name__ == '__main__': |
| 49 | + # begin |
| 50 | + s = Solution() |
| 51 | + print s.twoSum([3,2,4], 6) |
Collapse file
Copy file name to clipboardExpand all lines: python/__init__.py