java在数组中添加twoNumber,并且必须等于目标
我有一个程序,其中输入数组“n”的元素数,然后输入目标“d”, 然后我想从矩阵中加上两个数字,加起来等于目标“d”, 然后我想返回这两个数字的索引数组 例如:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
我写了这个程序,但是我不能返回索引, 我怎样才能解决这个问题
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
System.out.println("This the number that we want it" + "\n" + i + "\n" + j);
}
}
}
return nums;
}
# 1 楼答案
看看这个解决方案
时间复杂度
O(n^2)
,空间复杂度O(1)
时间复杂性
O(n)
,空间复杂性O(n)
# 2 楼答案
您需要创建一个大小为2的新数组并返回该数组
如果你对O(n^2)的复杂性感到满意,你不需要提前阅读。但这里有一个时间复杂度为O(n)的解决方案: