LeetCode 001 Two Sum - Java

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

 

定位:简单题
对于目标值,我们对原数组进行遍历,对于其中每个数字,再遍历后面所有,计算每两个数字之和,当等于目标值时返回。

 

Java实现:

 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         int len=nums.length;
 4         for(int i=0;i<len-1;i++){
 5             for(int j=i+1;j<len;j++){
 6                 if(nums[i]+nums[j]==target){
 7                     return new int[]{i,j};
 8                 }
 9             }
10         }
11         return new int[0];
12     }
13 }
posted @ 2017-06-03 22:04  仰恩  阅读(77)  评论(0编辑  收藏  举报