LeetCode 1 找出两个数之和
2015-09-08 19:53
246 查看
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
利用字典的查找优势,遍历一次输入,如果字典中存在target - nums[i]则结束,否则添加到字典.
c#
public class Solution {
public int[] TwoSum(int[] nums, int target)
{
int[] index=new int[2];
Dictionary<int,int> dict=new Dictionary<int,int>();
for(int i=0;i<nums.Length;i++)
{
if(dict.Keys.Contains(target-nums[i]))
{
index[0]=dict[target-nums[i]]+1;
index[1]=i+1;
break;
}
else
{
if(!dict.Keys.Contains(nums[i]))
dict.Add(nums[i],i);
}
}
return index;
}
}
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
利用字典的查找优势,遍历一次输入,如果字典中存在target - nums[i]则结束,否则添加到字典.
c#
public class Solution {
public int[] TwoSum(int[] nums, int target)
{
int[] index=new int[2];
Dictionary<int,int> dict=new Dictionary<int,int>();
for(int i=0;i<nums.Length;i++)
{
if(dict.Keys.Contains(target-nums[i]))
{
index[0]=dict[target-nums[i]]+1;
index[1]=i+1;
break;
}
else
{
if(!dict.Keys.Contains(nums[i]))
dict.Add(nums[i],i);
}
}
return index;
}
}
相关文章推荐
- C# 窗口实现Win7简单屏幕泡泡保护程序 和实现聊天窗口震动
- iOS开发:通讯录之复杂文本字符串解析
- 链表的经典技巧及算法
- 结构体类型定义的一般式
- 安装及设置MASM32 SDK
- JVM(java 虚拟机)内存设置
- 1019. 数字黑洞 (20)
- 结构体类型定义的一般式
- 汉字数字转化为阿拉伯数字
- Android-NDK环境搭建
- 题目1355:扑克牌顺子
- The differences between AngularJS $apply, $digest, and $evalAsync
- hdu 2035 人见人爱A^B
- Pyqtdeploy Android PyQtForAndroid 编译记录【更新中
- 1018. 锤子剪刀布 (20)
- 促进胎儿入盆试试运动法和调整姿势
- 胎儿入盆是什么感觉 怎样促进胎儿入盆
- HTTP - 条件请求
- Markdown编辑器写博客
- 第2周-跑道长度