LeetCode167 and 1 Two Sum

LeetCode Array 167 Two Sum

II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解读:给定一个升序数组,和一个目标值。求数组中哪两个元素相加会得到目标值。输出相应的索引+1.
分析:和Two Sum的思路一样,使用Map来存储数组元素,key为数组元素的值,value为数组元素的索引+1。(要求输出非零值)

public int[] twoSum(int[] numbers, int target) {
        Logger.getGlobal().info("获得数组"+Arrays.toString(numbers));
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            map.put(numbers[i], i + 1);
        }
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                return new int[]{i + 1, map.get(target - numbers[i])};
            }
        }
        throw new RuntimeException("无解!");
    }

I Two Sum 1
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].
分析:使用Map来存放数组元素,Map中containsKey函数查找target-nums[i]是否存在。

    public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> m=new HashMap<>();

        for (int i = 0; i <nums.length; i++) {
            m.put(nums[i],i);
        }
        int i=0,j=0;
        for (i = 0; i <nums.length ; i++) {
             int temp=target-nums[i];
             if(m.containsKey(temp)&&i!=m.get(temp))
             {
               // j=m.get(temp);
                //break;
                 return new int[]{i,m.get(temp)};
             }
        }
        throw new IllegalArgumentException("no two sum souletiomn");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值