• 1. Two Sum


    题目:给定一个整型数组,返回两个数的下标,满足两个数相加为一个特定整数。假定只有一个正确答案

    例如:

    nums = [2, 7, 11, 15], target = 9,因为nums[0] + nums[1] = 2 + 7 = 9,返回[0,1]

    思路:如果是只返回两个数,可以将数组排序后,从两边(left=0,right=length-1)往中间依次取数。如果总和大于target,right--,否则right++;直到left大于等于right停止。

    但本题要求返回索引,所以需要用一个map来记录每个数字出现的位置

    解法1:

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

    解法2:

     1     public int[] twoSum(int[] nums, int target) {
     2         if(nums == null || nums.length == 0)
     3             return null;
     4         Map<Integer,List<Integer>> numberMap = new HashMap<>();
     5         for (int i=0;i<nums.length;i++)
     6         {
     7             List<Integer> indexs = numberMap.getOrDefault(nums[i],new ArrayList<>());
     8             indexs.add(i);
     9             numberMap.put(nums[i],indexs);
    10         }
    11 
    12         for (Map.Entry<Integer,List<Integer>> e:numberMap.entrySet())
    13         {
    14             if (numberMap.containsKey(target - e.getKey()))
    15             {
    16                 if (target - e.getKey() == e.getKey())
    17                 {
    18                     continue;
    19                 }
    20                 return new int[]{e.getValue().get(0),numberMap.get(target - e.getKey()).get(0)};
    21             }
    22         }
    23         List<Integer> p = numberMap.get(target/2);
    24         if(p == null) return null;
    25         return new int[]{p.get(0),p.get(1)};   
    26     }
  • 相关阅读:
    6. Flask请求和响应
    5. Flask模板
    FW:Software Testing
    What is the difference between modified duration, effective duration and duration?
    How to push master to QA branch in GIT
    FTPS Firewall
    Query performance optimization of Vertica
    (Forward)5 Public Speaking Tips That'll Prepare You for Any Interview
    (转)The remote certificate is invalid according to the validation procedure
    Change
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7668327.html
Copyright © 2020-2023  润新知