【LeetCode】算法系列(Algorithms)(一)——2sum,3sum,3sum Closeset

2023-12-12 18:08

本文主要是介绍【LeetCode】算法系列(Algorithms)(一)——2sum,3sum,3sum Closeset,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本系列记录了博主在刷LeetCode过程中的笔记。更新于2019.5.13。

ps:今天是母亲节,祝所有的母亲们节日快乐,健康幸福!

文章目录

  • 1. 2Sum
    • 题目
    • 答案
  • 15. 3sum
    • 题目
    • 答案
  • 16. 3Sum Closest
    • 题目
    • 答案

1. 2Sum

题目难度: easy

题目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
给定一个由整数组成的array,返回和等于某个特定目标数的两个数的indices。You may assume that each input would have exactly one solution, and you may not use the same element twice.
可以假设每个输入只有一个特定的解,且一个元素只能用一次。Example:
例:Given nums = [2, 7, 11, 15], target = 9,
给定整数[2,7,11,15],目标数9。Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
因为nums[0]+nums[1]=2+7=9,所以返回[0,1]。

答案

方法1:暴力搜索
这个方案相信很多人都可以想到,即查询整个array,对每个元素 x x x都查找一下有没有元素等于 t a r g e t − x target-x targetx

Java答案:

public int[] twoSum(int[] nums, int target) {for (int i = 0; i < nums.length; i++) {for (int j = i + 1; j < nums.length; j++) {if (nums[j] == target - nums[i]) {return new int[] { i, j };}}}throw new IllegalArgumentException("No two sum solution");
}

方法2: Two-pass Hash Table
为了节省运算时间,需要有一个更有效的方法检查元素是否存在于array中。如果存在,需要找到该元素的index。那么什么是管理array内的每个元素到其index映射的最好方法呢?那就是hash table(哈希表)。

由此,我们以存储空间为代价,将查找时间从 O ( n ) O(n) O(n)下降到了 O ( 1 ) O(1) O(1)。具体实现方法是,首先建一个哈希表,随后查表。

Java答案:

public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {map.put(nums[i], i);}for (int i = 0; i < nums.length; i++) {int complement = target - nums[i];if (map.containsKey(complement) && map.get(complement) != i) {return new int[] { i, map.get(complement) };}}throw new IllegalArgumentException("No two sum solution");
}

在这里插入图片描述
方法3:其他方法

Python答案:

class Solution(object):def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""for i in range(len(nums)):search_num = target-nums[i]if search_num in nums:index_b = nums.index(search_num)if index_b != i:index_a = ireturn index_a,index_b

在这里插入图片描述

C++答案:

#include <unordered_map>
#include <vector>
using namespace std;class Solution
{
public:vector<int> twoSum(vector<int>& nums, int target){unordered_map<int, size_t> N;vector<int> res;for(size_t i = 0; i < nums.size(); ++i) {int num = nums[i];if(N.count(target - num)) {res.push_back(i);res.push_back(N[target - num]);} else {N.insert({ num, i });}}return res;}
};

在这里插入图片描述

15. 3sum

题目难度:Medium

题目

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
给定一个由n个整数组成的array,找到是否存在三个元素a,b,c之和等于0。
如果存在,找到所有不重复的组合。Note:
注意:The solution set must not contain duplicate triplets.
答案中的所有组合不能重复。Example:
例:Given array nums = [-1, 0, 1, 2, -1, -4],
给定矩阵nums = [-1, 0, 1, 2, -1, -4],A solution set is:
一个解是:
[[-1, 0, 1],[-1, -1, 2]
]

答案

没有官方答案,博主写的python代码,虽然不是暴力搜索但是仍然超出时间限制:

class Solution(object):def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""results = [];final_results = [];for i in range(len(nums)):for j in range(len(nums)):if i != j:num_search = -nums[i]-nums[j]if num_search in nums:index_n = nums.index(num_search)if index_n != i:if index_n != j:l = [nums[i],nums[j],num_search]l.sort()results.append(l)for i in range(len(results)):tmp = results[i]results[i] = ['a','a','a']if tmp in results:continueelse:final_results.append(tmp)
class Solution(object):def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""results = [];if len(nums) < 3:return resultsfor i in range(len(nums)):for j in range(len(nums[i+1:])):search_nums = -nums[i]-nums[i+j+1]if search_nums in nums[i+1:]:search_nums_index = nums[i+1:].index(search_nums)if j != search_nums_index:l = [nums[i],nums[i+j+1],search_nums]l.sort()if l in results:continueelse:results.append(l)return results

C++答案:
代码来自于这里。

class Solution {
public:vector< vector<int> > threeSum(vector<int>& nums) {int n = nums.size();vector< vector<int> > res;if (n < 3)return res;sort(nums.begin(), nums.end());for(int i = 0; i < n - 2; i++){if(i == 0 ||  (i > 0 && nums[i] != nums[i - 1])){int left = i + 1, right = n - 1;int sum = 0 - nums[i];while(left < right){if(nums[left] + nums[right] == sum){vector<int> vi;vi.push_back(nums[i]);vi.push_back(nums[left]);vi.push_back(nums[right]);res.push_back(vi);while(left < right && nums[left] == nums[left + 1])left++;while(left < right && nums[right] == nums[right - 1])right--;left++;right--;}else if(nums[left] + nums[right] < sum)left++;elseright--;}}}return res;}
};

在这里插入图片描述
但是博主尝试用相同的逻辑撰写Python代码,仍然超出时间限制:

class Solution(object):def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""results = []n = len(nums)nums.sort()for i in range(n):left = i+1right = n-1rest_num = -nums[i]while left < right:if nums[left]+nums[right]==rest_num:l = [nums[i],nums[left],nums[right]]if l in results:left=left+1right=right-1continueelse:results.append(l)left=left+1right=right-1elif nums[left]+nums[right]<rest_num:left = left+1else:right=right-1return results

正确Python代码,相同思路:

class Solution:# @return a list of lists of length 3, [[val1,val2,val3]]def threeSum(self, num):num.sort()res = []for i in range(len(num)-2):if i == 0 or num[i] > num[i-1]:left = i + 1; right = len(num) - 1while left < right:if num[left] + num[right] == -num[i]:res.append([num[i], num[left], num[right]])left += 1; right -= 1while left < right and num[left] == num[left-1]: left +=1while left < right and num[right] == num[right+1]: right -= 1elif num[left] + num[right] < -num[i]:while left < right:left += 1if num[left] > num[left-1]: breakelse:while left < right:right -= 1if num[right] < num[right+1]: breakreturn res

在这里插入图片描述

16. 3Sum Closest

题目难度:Medium

题目

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
给定一个由整数组成的array nums和一个目标整数target,找到nums中的三个整数,使得其和最接近target。
返回这三个整数的和。可以假设只存在一个解。Example:
例:Given array nums = [-1, 2, 1, -4], and target = 1.
给定array nums = [-1, 2, 1, -4]和目标target = 1The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
最接近目标的和应该是2:(-1 + 2 + 1 = 2)。

答案

Python答案:
以下为博主自己写的Python版本答案

class Solution(object):def threeSumClosest(self, nums, target):""":type nums: List[int]:type target: int:rtype: int"""nums.sort()tmp_left = []tmp_right = []for i in range(len(nums)-2):obj = target-nums[i]left = i+1; right = len(nums)-1while left<right:tmp = nums[left]+nums[right]if tmp == obj:return tmp+nums[i]elif tmp < obj:tmp_left.append(tmp + nums[i])left = left+1else:tmp_right.append(tmp + nums[i])right = right-1try:left_max = max(tmp_left)res_left = abs(left_max-target)left_exist = Trueexcept:left_exist = Falsetry:right_min = min(tmp_right)res_right = abs(right_min-target)right_exist = Trueexcept:right_exist = Falseif left_exist and not right_exist:return left_maxelif not left_exist and right_exist:return right_minelif left_exist and right_exist and res_left < res_right:return left_maxelif left_exist and right_exist and res_left > res_right:return right_minelse:print('Answer not found!')更多内容,欢迎加入星球讨论。
![在这里插入图片描述](https://img-blog.csdnimg.cn/2019070914030826.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1NodXFpYW9T,size_16,color_FFFFFF,t_70)

这篇关于【LeetCode】算法系列(Algorithms)(一)——2sum,3sum,3sum Closeset的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/485492

相关文章

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

哈希leetcode-1

目录 1前言 2.例题  2.1两数之和 2.2判断是否互为字符重排 2.3存在重复元素1 2.4存在重复元素2 2.5字母异位词分组 1前言 哈希表主要是适合于快速查找某个元素(O(1)) 当我们要频繁的查找某个元素,第一哈希表O(1),第二,二分O(log n) 一般可以分为语言自带的容器哈希和用数组模拟的简易哈希。 最简单的比如数组模拟字符存储,只要开26个c

不懂推荐算法也能设计推荐系统

本文以商业化应用推荐为例,告诉我们不懂推荐算法的产品,也能从产品侧出发, 设计出一款不错的推荐系统。 相信很多新手产品,看到算法二字,多是懵圈的。 什么排序算法、最短路径等都是相对传统的算法(注:传统是指科班出身的产品都会接触过)。但对于推荐算法,多数产品对着网上搜到的资源,都会无从下手。特别当某些推荐算法 和 “AI”扯上关系后,更是加大了理解的难度。 但,不了解推荐算法,就无法做推荐系

康拓展开(hash算法中会用到)

康拓展开是一个全排列到一个自然数的双射(也就是某个全排列与某个自然数一一对应) 公式: X=a[n]*(n-1)!+a[n-1]*(n-2)!+...+a[i]*(i-1)!+...+a[1]*0! 其中,a[i]为整数,并且0<=a[i]<i,1<=i<=n。(a[i]在不同应用中的含义不同); 典型应用: 计算当前排列在所有由小到大全排列中的顺序,也就是说求当前排列是第

csu 1446 Problem J Modified LCS (扩展欧几里得算法的简单应用)

这是一道扩展欧几里得算法的简单应用题,这题是在湖南多校训练赛中队友ac的一道题,在比赛之后请教了队友,然后自己把它a掉 这也是自己独自做扩展欧几里得算法的题目 题意:把题意转变下就变成了:求d1*x - d2*y = f2 - f1的解,很明显用exgcd来解 下面介绍一下exgcd的一些知识点:求ax + by = c的解 一、首先求ax + by = gcd(a,b)的解 这个

综合安防管理平台LntonAIServer视频监控汇聚抖动检测算法优势

LntonAIServer视频质量诊断功能中的抖动检测是一个专门针对视频稳定性进行分析的功能。抖动通常是指视频帧之间的不必要运动,这种运动可能是由于摄像机的移动、传输中的错误或编解码问题导致的。抖动检测对于确保视频内容的平滑性和观看体验至关重要。 优势 1. 提高图像质量 - 清晰度提升:减少抖动,提高图像的清晰度和细节表现力,使得监控画面更加真实可信。 - 细节增强:在低光条件下,抖

【数据结构】——原来排序算法搞懂这些就行,轻松拿捏

前言:快速排序的实现最重要的是找基准值,下面让我们来了解如何实现找基准值 基准值的注释:在快排的过程中,每一次我们要取一个元素作为枢纽值,以这个数字来将序列划分为两部分。 在此我们采用三数取中法,也就是取左端、中间、右端三个数,然后进行排序,将中间数作为枢纽值。 快速排序实现主框架: //快速排序 void QuickSort(int* arr, int left, int rig

poj 3974 and hdu 3068 最长回文串的O(n)解法(Manacher算法)

求一段字符串中的最长回文串。 因为数据量比较大,用原来的O(n^2)会爆。 小白上的O(n^2)解法代码:TLE啦~ #include<stdio.h>#include<string.h>const int Maxn = 1000000;char s[Maxn];int main(){char e[] = {"END"};while(scanf("%s", s) != EO

科研绘图系列:R语言扩展物种堆积图(Extended Stacked Barplot)

介绍 R语言的扩展物种堆积图是一种数据可视化工具,它不仅展示了物种的堆积结果,还整合了不同样本分组之间的差异性分析结果。这种图形表示方法能够直观地比较不同物种在各个分组中的显著性差异,为研究者提供了一种有效的数据解读方式。 加载R包 knitr::opts_chunk$set(warning = F, message = F)library(tidyverse)library(phyl

秋招最新大模型算法面试,熬夜都要肝完它

💥大家在面试大模型LLM这个板块的时候,不知道面试完会不会复盘、总结,做笔记的习惯,这份大模型算法岗面试八股笔记也帮助不少人拿到过offer ✨对于面试大模型算法工程师会有一定的帮助,都附有完整答案,熬夜也要看完,祝大家一臂之力 这份《大模型算法工程师面试题》已经上传CSDN,还有完整版的大模型 AI 学习资料,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费