当前位置: 首页 > news >正文

LeetCode- Two Sum

题目描述:
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。
本题有几种解法,比较普遍的是排序+二分查找。这里给出一种使用哈希表的解法。
1. 对数组nums遍历过程中存nums[i],和索引[i]。如果nums[i]已经出现过:
1.1 如果nums[i] = target/2,返回{hash[nums[i], i}
1.2 如果不等,直接忽略
2. 遍历哈希键值对,对每个键k判断hash[target-k]是否存在,如果存在并且hash[target-k]与hash[k]不相等(不是同一个位置),返回结果。
3. 返回时注意小索引在前,大的在后面。


实现代码:


public class Solution {
    public int[] TwoSum(int[] nums, int target) 
    {
        var hash = new Dictionary<int, int>();
    	for(var i = 0;i < nums.Length; i++){
    		if(!hash.ContainsKey(nums[i])){
    			hash.Add(nums[i], i);
    		}
    		else{
    			if(target == nums[i] * 2){
    				return new int[2]{hash[nums[i]] + 1, i + 1};
    			}
    			// if one number appears twice and not equals to target half , just take the first one
    		}
    	}
    	
    	foreach(var k in hash.Keys){
    		var k2 = target - k;
    		if(hash.ContainsKey(k2) && hash[k2] != hash[k]){
    			var index1 = hash[k];
    			var index2 = hash[k2];
    			
    			if(index1 > index2){
    				return new int[2]{index2 + 1, index1 + 1};
    			}else{
    				return new int[2]{index1 + 1, index2 + 1};
    			}
    		}
    	}
    	
    	return null;
    }
}


相关文章:

  • cognos8 关于密钥的问题
  • LeetCode --Word Break
  • LeetCode--H-Index
  • Leetcode--Lowest Common Ancestor of a Binary Search Tree
  • 参加Tibco的SOA应用及2009 IT架构趋势研讨会记
  • Leet 题目整理归类 - 快速通道 (持续更新)
  • 设计模式的阴谋论
  • c# mongodb driver 插入重复记录
  • 中国移动通信信息资源站实体与互联网短消息网关(ISMG)
  • MongoDB C# Driver 使用示例 (2.2)
  • C# GetHashCode 的实现方式
  • SCOPE_IDENTITY、IDENT_CURRENT 和 @@IDENTITY的区别比较
  • Dynamic Language Runtime (DLR) 初深
  • 2009 Webware 100 名单揭晓
  • DLR之 ExpandoObject和DynamicObject的使用示例
  • 【编码】-360实习笔试编程题(二)-2016.03.29
  • Android交互
  • CSS 提示工具(Tooltip)
  • ES6语法详解(一)
  • HTTP那些事
  • iOS 系统授权开发
  • iOS 颜色设置看我就够了
  • JS字符串转数字方法总结
  • leetcode46 Permutation 排列组合
  • node.js
  • vue-loader 源码解析系列之 selector
  • 百度小程序遇到的问题
  • 翻译--Thinking in React
  • 高性能JavaScript阅读简记(三)
  • 如何邀请好友注册您的网站(模拟百度网盘)
  • 微信公众号开发小记——5.python微信红包
  • CMake 入门1/5:基于阿里云 ECS搭建体验环境
  • 湖北分布式智能数据采集方法有哪些?
  • ​ 全球云科技基础设施:亚马逊云科技的海外服务器网络如何演进
  • (1)Android开发优化---------UI优化
  • (22)C#传智:复习,多态虚方法抽象类接口,静态类,String与StringBuilder,集合泛型List与Dictionary,文件类,结构与类的区别
  • (6)【Python/机器学习/深度学习】Machine-Learning模型与算法应用—使用Adaboost建模及工作环境下的数据分析整理
  • (草履虫都可以看懂的)PyQt子窗口向主窗口传递参数,主窗口接收子窗口信号、参数。
  • (层次遍历)104. 二叉树的最大深度
  • (二十四)Flask之flask-session组件
  • (附源码)springboot掌上博客系统 毕业设计063131
  • (论文阅读30/100)Convolutional Pose Machines
  • (三维重建学习)已有位姿放入colmap和3D Gaussian Splatting训练
  • (一)pytest自动化测试框架之生成测试报告(mac系统)
  • (转)详解PHP处理密码的几种方式
  • (转)原始图像数据和PDF中的图像数据
  • .NET 5种线程安全集合
  • .NET Standard 的管理策略
  • .NET4.0并行计算技术基础(1)
  • .Net6支持的操作系统版本(.net8已来,你还在用.netframework4.5吗)
  • .net使用excel的cells对象没有value方法——学习.net的Excel工作表问题
  • .NET微信公众号开发-2.0创建自定义菜单
  • .set 数据导入matlab,设置变量导入选项 - MATLAB setvaropts - MathWorks 中国
  • @manytomany 保存后数据被删除_[Windows] 数据恢复软件RStudio v8.14.179675 便携特别版...
  • [ element-ui:table ] 设置table中某些行数据禁止被选中,通过selectable 定义方法解决