两数只和(twoSum)

两数只和(twoSum)

点击链接加入群聊【java菜鸟学习】:https://jq.qq.com/?_wv=1027&k=5afU7nS
群号:124569404

  • 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。
  • 您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。
    由于需要考虑负数以及两个数字相同的情况,暂未想到很好的解决办法(Map不能存储相同的数字)

/**
 * ClassName: Twosum
 *
 * @author leegoo
 * @Description:
 * @date 2019年01月09日
 */
public class Twosum {
    /**
     * Given an array of integers, return indices of the two numbers such that they add up to a specific target.
     * <p>
     * You may assume that each input would have exactly one solution, and you may not use the same element twice.
     * Example:
     * <p>
     * Given nums = [2, 7, 11, 15], target = 9,
     * <p>
     * Because nums[0] + nums[1] = 2 + 7 = 9,
     * return [0, 1].
     *
     * @param args
     */
    public static void main(String[] args) {
        int[] nums = new int[]{3,2,4};
        int target = 6;
        int[] ints = twoSum(target, nums);
    }

    public static int[] twoSum(int target, int[] nums) {
        int[] res = new int[]{0, 0};
        outloop:
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (i != j && nums[i] + nums[j] == target) {
                    res[0] = i;
                    res[1] = j;
                    break outloop;
                }
            }
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值