题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
代码:
/**
* 给定一个整数数组 nums 和一个目标值 target,<br/>
* 请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。<br/>
* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 <br/>
*/
public class TwoSum {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8};
int[] nums1 = twoSum(nums, 5);
System.out.print("[");
if (nums1 != null) {
for (int i = 0; i < nums1.length; i++
) {
if (i == nums1.length - 1) {
System.out.print(nums1[i]);
} else {
System.out.print(nums1[i] + ",");
}
}
}
System.out.print("]");
}
public static int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[]{i, j};
}
}
}
return null;
}
}