LeetCode(1)--TwoSum

Question:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

个人思路:

1、计算当前元素目标值的差值
2、查询差值数组中的下标。

代码实现如下:

    /**
     * 获取数组中任意两个元素之和等于target的下标
     * @param nums 数组
     * @param target 目标值
     * @return 两个元素的下标
     */
    public static int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        int[] result = new int[2];
        for (int i = 0; i < length; i++) {
            int differenceValue = target - nums[i];
            int index = getIndex(nums, differenceValue, i);
            if (index != -1) {
                result[0] = i;
                result[1] = index;
                return result;
            }
        }
        return null;
    }

    /**
     * 获取数组中某元素的下标
     * @param nums 数组
     * @param value 当前元素与目标值的差值
     * @param currentNumIndex 当前元素的下标
     * @return 元素在数组中的下标
     */
    public static int getIndex(int[] nums, int value, int currentNumIndex) {
        int index = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == value && i != currentNumIndex) {
                index = i;
                break;
            }
        }
        return index;
    }

LeetCode的参考答案:

/**
 * 该方法很妙,先将数组元素添加至Map集合,直到在集合中找到与当前元素和为target的元素,并返回下标
 * @param nums
 * @param target
 * @return
 */
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

/**
 * 该方法属于蛮力法,一个个去试,直到满足条件
 * @param nums
 * @param target
 * @return
 */
public 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 };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

总结:

自己思考问题缺少全局观,限定自己的思维在具体的步骤上,解决方案不够灵活,
总觉得数组要在有序的情况下才能很好地操作;也说明自己见得太少,想法太少。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值