Java两个数的和
给你一个整数数组, 返回两个数的指数,使他们加起来等于给定的数.
你可以假设只有一个解, 并且相同的元素不会用两次.
比如:
给定数组 = [2, 7, 11, 15], 目标数 = 9, 因为[0] + nums[1] = 2 + 7 = 9, 返回 [0, 1].
下面是我的代码.
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] temp = {};
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
temp = new int[] { i, j };
return temp;
}
}
}
return temp;
}
}