我正在处理leetcode(Two Sum)上的问题:
给定一个整数数组,返回两个数字的索引 他们加起来就是一个特定的目标。
您可以假设每个输入都只有一个解决方案,并且 你可能不会两次使用相同的元素。
示例:给定nums = [2,7,11,15],target = 9,
因为nums [0] + nums [1] = 2 + 7 = 9,所以返回[0,1]。
我尝试了自己的解决方案,数组总是显示[0,0]。所以我尝试了一个他们在几次调整后得到的解决方案,当我把它放入时仍然显示[0,0]并且它是排名最高的解决方案。是我还是leetcode? p>
原始解决方案:
import java.util.Arrays;
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
for(int i = 0; i < nums.length-1; i++)
{
for(int j = i+1; j < nums.length-1; j++)
{
if(target == (nums[i] + nums[j]))
{
indices[0] = i+1;
indices[1] = j+1;
}
}
}
return indices;
}
}
Leetcode解决方案:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length-1; i++)
{
if(map.containsKey(target - nums[i]))
{
indices[1] = i + 1;
indices[0] = map.get(target - nums[i]);
return indices;
}
map.put(nums[i], i + 1);
}
return indices;
}
}
我不明白为什么这些都不会在indices数组中注册int,它会不断地为这两个解返回[0,0]。
答案 0 :(得分:0)
查看我的代码。也许它会更清楚,我想说的是: - )
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[] result = solution.twoSum(new int[] { 2, 7, 11, 15 }, 17);
System.out.println(result[0] + "/" + result[1]);
}
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (i == j) {
//do not use the same index for sum
continue;
}
if (target == (nums[i] + nums[j])) {
indices[0] = i;
indices[1] = j;
}
}
}
return indices;
}
}
答案 1 :(得分:0)
循环遍历数组中两个组合的最简单方法可以按如下方式完成:
for(int i=0 ; i<nums.length-1 ; i++)
for(int j=i+1 ; j<nums.length ; j++)
if(nums[i]+nums[j]==target)
return new int[] {i, j};
return null; //in case there's no such case