前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode 打卡,1. 两数之和

leetcode 打卡,1. 两数之和

作者头像
我乃小神神
发布2022-05-11 08:47:50
2040
发布2022-05-11 08:47:50
举报
文章被收录于专栏:前端基础

单纯记录一下自己要刷题的日子 2022年5月10号 目前凌晨12:14

代码语言:javascript
复制
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		输入:nums = [2,7,1,15], target = 9
		输出:[0,1]

	</body>
	<script>
		let nums = [2, 7, 0, 3, 4]
		let target = 9
		// 1:使用map 解
		var oneSum = function(nums, target) {
			const map = new Map()
			for (let i = 0; i < nums.length; i++) {
				const otherIndex = map.get(target - nums[i])
				if (otherIndex !== undefined) {
					//能匹配到返回当前map 中的value,及其当前的下标
					return [otherIndex, i]
				}
				//先存起来
				map.set(nums[i], i)
			}
		};
		console.log("1:使用map 解", oneSum(nums, target))
		// 2:直接for 循环匹配差值
		var twoSum = function(nums, target) {
			for (let i = 0; i < nums.length; i++) {
				let num = target - nums[i]
				let res1 = i
				let res2 = nums.indexOf(num, i + 1);
				if (res2 !== -1) {
					return [res1, res2]
				}
			}
		};
		console.log("2.直接for 循环匹配差值", twoSum(nums, target))
		// 3:直接for 循环
		var threeSum = function(nums, target) {
			for (let i = 0, len = nums.length; i < len - 1; i++) {
				for (let j = i + 1; j < len; j++) {
					if (nums[i] + nums[j] == target) {
						return [i, j]
					}
				}
			}
		};
		console.log("3:直接for 循环", threeSum(nums, target))
		// 4:map 哈希
		var fourSum = function(nums, target) {
		    const map = new Map()
		    for(let i = 0; i < nums.length; i++) {
		        const d = target - nums[i]
		        if(map.has(d)) {
		            return [map.get(d), i]
		        }
		        map.set(nums[i], i)
		    }
		};
		console.log("4:map 哈希", fourSum(nums, target))
		
	</script>
</html>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档