(leetcode)1. 查找数组中两个数之和为给定值Two Sum---Java

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.

给定一个整数数组,返回两个数字的索引,使得它们相加到一个特定的目标。

您可以假设每个输入都有一个解决方案。

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [01].

 我的解法:思路是把数组装进arraylist列表里面,然后做一次循环,每次用列表里面的第i个数和后面的第n-i个数做判断。这样做没有最快的答案好,但是思路是一样的,原因在于,

我是先一次性全部放进去,这里花时间。然后,每次比较,我又取了全部list的子列表arraylist,这里也花时间。

public int[] twoSum(int[] nums, int target) {
      List<Integer>s = new ArrayList<Integer>();
      int len = nums.length;
      for(int i=0;i<len;i++){
            s.add(nums[i]);
      }
      
      //Collections.sort(s);
      
      for(int i=0;i<len-1;i++){
  //              System.out.println(i+" i  " +  len+ "  len");
 //               System.out.println(s.subList(i+1, len)+"    "+(target-nums[i]));
            if(s.subList(i+1, len).contains(target-nums[i])){
                  int[]res = new int[2];
                  res[0] = i;
                  res[1] = 1+i+s.subList(i+1, len).indexOf(target-nums[i]);
                  return res;
            }
      }
      return null;
    }

标准算法:

   
   
    public int[] twoSum2(int[] numbers, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                result[1] = i ;
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            map.put(numbers[i], i );
        }
        return result;
    }

放在hashmap里面,这样,在找到值的时候,去找对应的键就很快,比arraylist中的indexof要快,
另外,采用倒叙的方式,每次比较,比不到就加一个,加一个比截取一大段复杂度要低很多。
发布了32 篇原创文章 · 获赞 17 · 访问量 8万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章