【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

相关文章

使用雪花算法产生id导致前端精度缺失问题解决方案

《使用雪花算法产生id导致前端精度缺失问题解决方案》雪花算法由Twitter提出,设计目的是生成唯一的、递增的ID,下面:本文主要介绍使用雪花算法产生id导致前端精度缺失问题的解决方案,文中通过代... 目录一、问题根源二、解决方案1. 全局配置Jackson序列化规则2. 实体类必须使用Long封装类3.

Springboot实现推荐系统的协同过滤算法

《Springboot实现推荐系统的协同过滤算法》协同过滤算法是一种在推荐系统中广泛使用的算法,用于预测用户对物品(如商品、电影、音乐等)的偏好,从而实现个性化推荐,下面给大家介绍Springboot... 目录前言基本原理 算法分类 计算方法应用场景 代码实现 前言协同过滤算法(Collaborativ

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

springboot+dubbo实现时间轮算法

《springboot+dubbo实现时间轮算法》时间轮是一种高效利用线程资源进行批量化调度的算法,本文主要介绍了springboot+dubbo实现时间轮算法,文中通过示例代码介绍的非常详细,对大家... 目录前言一、参数说明二、具体实现1、HashedwheelTimer2、createWheel3、n

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

Java时间轮调度算法的代码实现

《Java时间轮调度算法的代码实现》时间轮是一种高效的定时调度算法,主要用于管理延时任务或周期性任务,它通过一个环形数组(时间轮)和指针来实现,将大量定时任务分摊到固定的时间槽中,极大地降低了时间复杂... 目录1、简述2、时间轮的原理3. 时间轮的实现步骤3.1 定义时间槽3.2 定义时间轮3.3 使用时

如何通过Golang的container/list实现LRU缓存算法

《如何通过Golang的container/list实现LRU缓存算法》文章介绍了Go语言中container/list包实现的双向链表,并探讨了如何使用链表实现LRU缓存,LRU缓存通过维护一个双向... 目录力扣:146. LRU 缓存主要结构 List 和 Element常用方法1. 初始化链表2.

golang字符串匹配算法解读

《golang字符串匹配算法解读》文章介绍了字符串匹配算法的原理,特别是Knuth-Morris-Pratt(KMP)算法,该算法通过构建模式串的前缀表来减少匹配时的不必要的字符比较,从而提高效率,在... 目录简介KMP实现代码总结简介字符串匹配算法主要用于在一个较长的文本串中查找一个较短的字符串(称为

通俗易懂的Java常见限流算法具体实现

《通俗易懂的Java常见限流算法具体实现》:本文主要介绍Java常见限流算法具体实现的相关资料,包括漏桶算法、令牌桶算法、Nginx限流和Redis+Lua限流的实现原理和具体步骤,并比较了它们的... 目录一、漏桶算法1.漏桶算法的思想和原理2.具体实现二、令牌桶算法1.令牌桶算法流程:2.具体实现2.1

Python中的随机森林算法与实战

《Python中的随机森林算法与实战》本文详细介绍了随机森林算法,包括其原理、实现步骤、分类和回归案例,并讨论了其优点和缺点,通过面向对象编程实现了一个简单的随机森林模型,并应用于鸢尾花分类和波士顿房... 目录1、随机森林算法概述2、随机森林的原理3、实现步骤4、分类案例:使用随机森林预测鸢尾花品种4.1