Leetcode-1:Two Sum

来源:互联网 发布:mac如何用搜狗输入法 编辑:程序博客网 时间:2024/06/12 20:40

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

Answer:

public class Solution {    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 };                }            }        }        return null;    }}