问题:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
很简单:
public class Test04 {
public static void main(String[] args) {
Integer[] a = {1, 2, 3, 4, 5, 6};
Integer[]b;
b= sum(a,7);
System.out.println();
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
public static Integer[] sum(Integer[] arr, Integer target) {
Integer[] tarNum = new Integer[arr.length];
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (i + 1 < arr.length) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == target) {
tarNum[count] = i;
count++;
tarNum[count] = j;
count++;
}
}
}
}
return tarNum;
}
}
哈希表算法,O(n)
public class Test16 {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int[] numsResult = twoSum(nums, 9);
for (int i : numsResult) {
System.out.println(i);
}
}
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer>map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int count = target- nums[i];
if(map.containsKey(count)){
return new int[]{map.get(count), i};
}
map.put(nums[i], i);
}
return new int[]{};
}
}
我要刷100道算法题,第4道!!