数组未注册添加的int

时间:2017-06-21 18:45:18

标签: java arrays

我正在处理leetcode(Two Sum)上的问题:

  

给定一个整数数组,返回两个数字的索引   他们加起来就是一个特定的目标。

     

您可以假设每个输入都只有一个解决方案,并且   你可能不会两次使用相同的元素。

     

示例:给定nums = [2,7,11,15],target = 9,

     

因为nums [0] + nums [1] = 2 + 7 = 9,所以返回[0,1]。

我尝试了自己的解决方案,数组总是显示[0,0]。所以我尝试了一个他们在几次调整后得到的解决方案,当我把它放入时仍然显示[0,0]并且它是排名最高的解决方案。是我还是leetcode?

原始解决方案:

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]。

2 个答案:

答案 0 :(得分:0)

  1. 根据我的理解,你的内部循环不能以i + 1开头,因为你必须检查数组中的每个索引。只有当内圈和外圈的索引匹配时,你应该跳过它,因为你不会自己添加索引。
  2. 你必须将你的数组循环到最后(所以我删除了for-statement中的-1)
  3. 如果找到匹配,为什么要返回i + 1和j + 1? (所以我删除了这个)
  4. 查看我的代码。也许它会更清楚,我想说的是: - )

    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