给定一数找出数组内哪两项相加等于该数

如数组{2,7,11,15} 与9 数组内0,1项相加为9
代码如下:
一暴力破解:

public static int[] f(int nums[],int target) {
		int[] res = new int[2];
		for(int i=0;i<nums.length;i++) {
			for(int j=0;j<nums.length;j++) {
				if(i!=j && nums[i]+nums[j] ==target) {
					res[0] = i;
					res[1] = j;
				} 
			}
		}

两次for循环遍历出结果
二 使用hashmap:

public static int[] F(int nums[],int target) {
		HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
		int[] res = new int[2];
		for(int i=0;i<nums.length;i++) {
			int c = target - nums[i]; 
			if(map.containsKey(nums[i])) {
				res[0] = map.get(nums[i]);
				res[1] = i;
			}else {
				map.put(c, i);
			}	
		}

只需要一次for循环
思路:以该数与数组内数据相减并将差值存入map内 判断map内数据是否与数组内数据相等 若相等则找到

发布了35 篇原创文章 · 获赞 0 · 访问量 663

猜你喜欢

转载自blog.csdn.net/Azadoo/article/details/104543106