首页 > 代码库 > LeetCode 1. Two Sum (两数之和)

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

 


题目标签:Array

  这道题目给了我们一个target, 要我们从array里找到两个数相加之和等于这个target。简单粗暴search, 两个for loop,遍历array,每次的 用target 减去当前数字, 在剩下的array里取找。

 

 

Java Solution:

Runtime beats 40.09% 

完成日期:03/09/2017

关键词:Array

关键点:Brute force search

 

 1 public class Solution 
 2 {
 3     public int[] twoSum(int[] nums, int target) 
 4     {
 5         int [] res = new int[2];
 6         
 7         for(int i=0; i<nums.length; i++)
 8         {
 9             int m = target - nums[i];;
10             
11             for(int j=i+1; j<nums.length; j++)
12             {
13                 if(nums[j] == m)
14                 {
15                     res[0] = i;
16                     res[1] = j;
17                     return res;
18                 }
19             }
20             
21         }
22         
23         return res;
24     }
25 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

LeetCode 1. Two Sum (两数之和)