LeetCode 1 找出两个数之和
来源:互联网 发布:java 用户登录次数 编辑:程序博客网 时间:2024/06/10 04:16
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;
}
}
- LeetCode 1 找出两个数之和
- 找出数组中两个数之和为指定的数
- leetcode 1: 找出两个数相加等于给定数 two sum
- leetcode 1 Two Sum(在无序数组中找两个数之和与目标值相等)
- 求两个数之和
- 两个数之和
- 找出升序数组中元素之和最接近于给定数值的两个数
- 面试算法题:数组中两个数之和为定值,找出这对数的下标
- 【算法世界】(八)找出数组中的两个数,使得二者之和为特定值target
- [Leetcode #1]Two Sum 从数组中找出和为特定值的两个数
- 给出一个数和一个有序数组,找出该数组中之和等于该数的两个数
- leetcode 1 Two Sum 两数之和
- LeetCode | 两数之和
- 快速找出一个数组中的两个数字,使两个数之和 等于一个已给定的值
- leetcode 1 Two Sum(在无序数组中找两个数之和与目标值相等,两种方法)
- LeetCode 之 two Sum寻找两个相加之和为给定值的两个数
- 找出不同的两个数
- 两个数之和等于目标数
- hdu 2035 人见人爱A^B
- 数据存储:ContentProvider获取联系人
- iOS开发:通讯录之复杂文本字符串解析
- 结构体类型定义的一般式
- 1019. 数字黑洞 (20)
- LeetCode 1 找出两个数之和
- C# 窗口实现Win7简单屏幕泡泡保护程序 和实现聊天窗口震动
- What is VEX ?
- 深入学习微框架 Spring Boot
- java 正则表达式
- Linux USB驱动框架分析
- Java内存与垃圾回收调优
- 源码阅读:SDWebImage
- Unity中使用UGUI与ScrollView的练习