LeetCode 1. Two Sum(Java)

2017-01-14 08:43:41来源:CSDN作者:Davy_Joe人点击

原题:
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].


题意:
输入一组整数,找出其可以相加等于target的两个数,并返回它们的下标。


思路:
思路很简单,遍历数组,按部就班,找到时返回下标即可。


代码:

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

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台