Problem 1 : Two Sum

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.


简单题,原本以为会考虑输入过于庞大的时间复杂度问题,实际上没有设坑,一次就通过了。

解法:二重循环暴力枚举

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int i = 0;
        int j = 0;
        outer: for (i = 0; i < nums.length; i++) {
            for (j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target)
                    break outer;
            }
        }
        int[] arr = { i, j };
        return arr;
    }
}

发布者

VC-Robot

游戏爱好者,动漫迷,C++修炼中,编程菜鸟,随性

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.