给定一个数组和一个目标值,找出和为目标值的整数,并返回他们的下标

参考力扣第一题

public class TestSum {

	int[] arrs = {19,15,88,65,105,858,645,145,868,2,35,78,66,7,159};
	int target = 9;
	public static void main(String[] args) {
		TestSum ts = new TestSum();
//		ts.calSum();d
//		int[] result = ts.retResult1();
		int[] result = ts.retResult2();
		for (int i = 0; i < result.length; i++) {
			System.out.println(result[i]);
		}
	}

	public int[] retResult1(){
		for (int i = 0; i < arrs.length; i++) {
			for(int j = i + 1; j < arrs.length; j++){
				//都可以
//				if(target - arrs[i] == arrs[j]){
				if(arrs[i] + arrs[j] == target){
					return new int[]{i,j};
				}
			}
		}
		return null;
	}
	
	public int[] retResult2(){
		Map<Integer,Integer> map = new HashMap<>();
		for (int i = 0; i < arrs.length; i++) {
			int tem = target - arrs[i];
			if(map.containsKey(tem)){
				return new int[]{map.get(tem),i};
			}
			map.put(arrs[i], i);
		}
		return null;
	}
}
posted @ 2021-07-13 14:41  卡卡罗特琪琪  阅读(191)  评论(0编辑  收藏  举报