TwoSum
package leetcode;


//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.

public class TwoSum {
    public int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        int firstIndex = 0;
        int secondIndex = 1;
        while (!isRightNums(nums[firstIndex], nums[secondIndex], target)){
            if (secondIndex < length) secondIndex ++;
            if (secondIndex == length){
                firstIndex ++;
                secondIndex = firstIndex + 1;
            }
            if (firstIndex == (length -1)) throw new IllegalArgumentException("No two sum solution");
        }
        return new int[]{firstIndex, secondIndex};
    }

    private boolean isRightNums(int num1, int num2, int target){
        return num1 + num2 == target;
    }

    public static void main(String[] args) {
        TwoSum ts = new TwoSum();
        int[] testNums = new int[]{2, 7, 11, 15};
        int[] result = ts.twoSum(testNums, 26);
        for (int res : result){
            System.out.println(res);
        }
    }

}
阅读更多
文章标签: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

TwoSum

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭