当前位置:   article > 正文

leetcode02-Two Sum

leetcode02-Two Sum

这道题目最直接的方法就是for循环俩次遍历数组,第二次遍历用target减去对应的值然后看数组中是否有该值,这种的解法时间复杂度是O(n^2)。我们想一下之所以需要二次遍历的原因是因为没有办法在O(1)的时间内判断出差值是否存在于该数组中,如果有的话其实遍历一次数组就可以了,O(1)时间复杂度判断一个数字是否存在?没错,有现成的数据结构能够满足我们的诉求,用map

import java.util.HashMap;
public class twoSum{
	public static void main(String[] args) {
		int[] arr = {2,7,11,15};
		int[] brr = getIdx(arr,9);
		if(brr.length > 0) {
			System.out.println(brr[0]);
			System.out.println(brr[1]);
		}
	}
	public static int[] getIdx(int[] arr,int target) {
		HashMap<Integer,Integer> mp = new HashMap();
		for(int i = 0;i<arr.length;i++) {
			mp.put(arr[i],i);
		}
		int[] res = new int[2];
		for(int i = 0;i<arr.length;i++) {
			if(mp.containsKey(target-arr[i]) && i != mp.get(target-arr[i])) {
				res[0] = i;
				res[1] = mp.get(target-arr[i]);
				return res;
			}
		}
		return res;
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/329455
推荐阅读
相关标签
  

闽ICP备14008679号