码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 1. Two Sum (两数之和)

时间:2017-07-11 23:20:58      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:esc   ret   tco   http   des   for loop   日期   nbsp   两数之和   

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 (两数之和)

标签:esc   ret   tco   http   des   for loop   日期   nbsp   两数之和   

原文地址:http://www.cnblogs.com/jimmycheng/p/7152458.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!