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

LeeCode 第1题

时间:2017-04-18 10:01:49      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:ima   margin   for   exception   重复   ble   pre   closed   思路   

要求:

  给定一个整数(int)数组(Array)和一个目标数值(Target),找出数组中两数之和等于目标值(target)的两个元素的下标位置,

假设:结果唯一,数组中元素不会重复。

 

本人思路:分别正序、倒序遍历数组求得结果。

代码如下:

技术分享
public class Solution {
    public int[] TwoSum(int[] nums, int target) {
       
        for(int i=0;i<nums.Length;i++)
        {
            for(int j=nums.Length-1;j>0;j--)
            {
                if(nums[i]+nums[j]==target)
                {
                    return new int[]{i,j};
                }
            }
             
        }
         throw new Exception("没有答案");
    }
}
View Code

   执行时长:技术分享这。。。    

   

  最优方法:  

技术分享
public class Solution {
    public int[] TwoSum(int[] nums, int target) {
       
       
            Dictionary<int, int> dic = new Dictionary<int, int>();

            for (int i = 0; i < nums.Length; i++)
            {
                int tag = target - nums[i];
                if (dic.ContainsKey(tag))
                {
                    return new int[] { dic[tag], i };
                }
                else
                {
                    dic.Add(nums[i], i);
                }

            }

            throw new Exception("没有答案");
    }
}
View Code

  执行时长:技术分享

  

  个人总结:多思考题干,多探索解决方案。

 

  题目原文: Two Sum

 

  题目解析: Two Sum Solution

 

LeeCode 第1题

标签:ima   margin   for   exception   重复   ble   pre   closed   思路   

原文地址:http://www.cnblogs.com/bro-ma/p/6722941.html

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