当前位置:网站首页>349两个数组的交集和01两数之和
349两个数组的交集和01两数之和
2022-07-27 10:33:00 【懒虫虫~】
一、01两数之和
1.1 题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
分析:
题意就是让你从数组中找到两个位置他们对应位置的和为target。
1.2 实现
public class TwoSum {
public static void main(String[] args) {
int[] nums1 = {
4,9,5};
int[] res = twoSum(nums1, 9);
System.out.println(res[0]);
System.out.println(res[1]);
}
public static int[] twoSum(int[] nums, int target) {
//利用map结构,key存储数值,value存储下标
int[] res = new int[2];
if(nums == null || nums.length == 0){
return res;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[1] = i;
res[0] = map.get(temp);
}
map.put(nums[i], i);
}
return res;
}
}
二、01两数之和
2.1 题目
给定两个数组,编写一个函数来计算它们的交集。
示例1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例1:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
2.2 实现
/**349. 两个数组的交集**/
public class Intersection {
/** * 创建set集合,利用其具有去重的特点进行筛选 * 创建nums集合,用于存储交集不重复的元素 * 循环遍历数组2,如果set中包含有数组2的元素,则将这个元素加入到set2中 * 遍历set集合,将结果存储在数组 */
public static void main(String[] args) {
int[] nums1 = {
4,9,5};
int[] nums2 = {
9,4,9,8,4};
System.out.println(Arrays.toString(intersection2(nums1, nums2)));
}
// 方法1:Set集合
public static int[] intersection1(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>(); // HashSet特性:无序、不重复、无索引。
Set<Integer> set2 = new HashSet<>();
for(int i = 0; i < nums1.length; i++){
set1.add(nums1[i]);
}
for(int i = 0; i < nums2.length; i++){
if(set1.contains(nums2[i])){
set2.add(nums2[i]);
}
}
int[] nums = new int[set2.size()];
int k = 0;
for(Integer it : set2){
nums[k++] = it;
}
return nums;
}
// 方法2:Map集合
public static int[] intersection2(int[] nums1, int[] nums2) {
// 创建map集合
Map<Integer, Integer> map = new HashMap<>();
// 将数组1中的元素全部加入到map集合中,并将其值默认为1,相当于做了去重的操作
for(int i = 0; i < nums1.length; i++){
map.put(nums1[i], 1);
}
// 创建list集合,用于存储结果
ArrayList<Integer> list = new ArrayList<>();
// 循环遍历数组2,如果map中包含数组2的元素,且其value大于0,则将其加入到list集合中,更新其value
for(int j = 0; j < nums2.length; j++){
if(map.containsKey(nums2[j]) && map.get(nums2[j]) > 0){
list.add(nums2[j]);
map.put(nums2[j], map.get(nums2[j]) - 1);// 将其value更新,也就是对其-1,相当于去重
}
}
// 创建数组,用于存放结果,将list中的元素赋值给数组,并返回
int len = list.size();
int[] res = new int[len];
for(int i = 0; i < len; i++){
res[i] = list.remove(0);
}
return res;
}
}
边栏推荐
- 基于FPGA的ECG信号采集,存储以及传输系统verilog实现
- Solved syntaxerror: (Unicode error) 'Unicode scape' codec can't decode bytes in position 2-3: truncated
- Cancer DDD
- 学习笔记-简易服务器实现
- Internal and external troubles of digital collection NFT "boring ape" bayc
- Data assets are king. How to analyze the relationship between enterprise digital transformation and data asset management?
- GEE中下载过程中出现 Error: Image.clipToBoundsAndScale, argument 'input'
- Compete for the key battle of stock users and help enterprises build a perfect labeling system - 01 live review
- Background color style modification on table hover in antd
- Tdengine helps Siemens' lightweight digital solution simicas simplify data processing process
猜你喜欢

Use of pyquery

Overview of user space lock on mobile platform

Play with the cluster configuration center and learn about the Taier console

Chengying, kangaroo cloud one-stop fully automated operation and maintenance steward, is officially open source

Use of beautifulsoup

Use kaggle to run Li Hongyi's machine learning homework

Views, triggers and stored procedures in MySQL

c语言指针函数和函数指针的辨析

Redis high availability principle

Use of parsel
随机推荐
MySQL index, transaction and storage engine
Internal and external troubles of digital collection NFT "boring ape" bayc
Use kaggle to run Li Hongyi's machine learning homework
Taishan Office Technology Lecture: scaling and opening files
Analysis of new communication security risks brought by quantum computer and Countermeasures
JVM judges that the object is dead, and practices verify GC recycling
ECCV 2022 | 同时完成四项跟踪任务!Unicorn: 迈向目标跟踪的大统一
Customized modification based on jira7.9.2
Codeforces Round #807 (Div 2.) AB
神经网络学习笔记
How to create a.Net image with diagnostic tools
NFT leaderboard -nft real offer latest address: NFT leaderboard.com
How to assemble a registry
9 UAV array
DNS principle and resolution process
Detailed explanation of status code meaning
Study notes Minio
Time and power allocation method to ensure fairness in sensor fusion system
发动机悬置系统冲击仿真-瞬时模态动态分析与响应谱分析
Chunjun supports DDL conversion and automatic execution of heterogeneous data sources - dtmo 02 review (including course playback + courseware)