描述

https://leetcode-cn.com/problems/two-sum/
image.png

我的解

  1. class Solution {
  2. public int[] twoSum(int[] nums, int target) {
  3. Map<Integer, List<Integer>> map = new HashMap<>();
  4. for (int i = 0; i < nums.length; i++) {
  5. int num = nums[i];
  6. if (map.containsKey(target - num)) {
  7. int[] ans = new int[2];
  8. List<Integer> list = map.get(target - num);
  9. ans[0] = i;
  10. for (int j : list) {
  11. if (j != i) {
  12. ans[1] = j;
  13. return ans;
  14. }
  15. }
  16. }
  17. map.putIfAbsent(num, new ArrayList<>());
  18. map.get(num).add(i);
  19. }
  20. return new int[2];
  21. }
  22. }

image.png

次优解

  1. class Solution {
  2. public int[] twoSum(int[] nums, int target) {
  3. Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
  4. for (int i = 0; i < nums.length; ++i) {
  5. if (hashtable.containsKey(target - nums[i])) {
  6. return new int[]{hashtable.get(target - nums[i]), i};
  7. }
  8. hashtable.put(nums[i], i);
  9. }
  10. return new int[0];
  11. }
  12. }

image.png

最优解

  1. class Solution {
  2. public int[] twoSum(int[] nums, int target) {
  3. int len = nums.length;
  4. int hlen = len/2;
  5. int toFind1;
  6. int toFind2;
  7. int bu;
  8. for (int i = 0; i < hlen; i++) {
  9. bu = len-i-1;
  10. toFind1 = target - nums[i];
  11. toFind2 = target - nums[bu];
  12. for (int j = i + 1; j < len; j++) {
  13. if (nums[j]==toFind1) {
  14. return new int[]{i,j};
  15. }
  16. if(nums[j]==toFind2){
  17. return new int[]{j,bu};
  18. }
  19. }
  20. }
  21. return null;
  22. }
  23. }