当前位置:网站首页>442. 数组中重复的数据
442. 数组中重复的数据
2022-07-01 10:08:00 【hequnwang10】
一、题目描述
给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 一次 或 两次 。请你找出所有出现 两次 的整数,并以数组形式返回。
你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间的算法解决此问题。
示例 1:
输入:nums = [4,3,2,7,8,2,3,1]
输出:[2,3]
示例 2:
输入:nums = [1,1,2]
输出:[1]
示例 3:
输入:nums = [1]
输出:[]
二、解题
一次遍历
正负号判断法,出现过的数字就数字取反,然后判断是否取反过。
class Solution {
public List<Integer> findDuplicates(int[] nums) {
//这题需要使用一次遍历 然后使用额外空间的算法
int length = nums.length;
List<Integer> res = new ArrayList<>();
for(int i = 0;i<length;i++){
int num = Math.abs(nums[i]);
if(nums[num-1] > 0){
nums[num-1] = -nums[num-1];
}else{
res.add(num);
}
}
return res;
}
}
时间复杂度:O(n)
空间复杂度:O(1)。
边栏推荐
- Huawei accounts work together at multiple ends to create a better internet life
- scratch大鱼吃小鱼 电子学会图形化编程scratch等级考试二级真题和答案解析2022年6月
- It is interesting to understand MMAP in this way!
- Cortex M4 systick details
- 关于#数据库#的问题:GBase 8s中如何避免死锁
- SQL SERVER2014删除数据库失败,报错偏移量0x0000...
- SQL 化是 ETL 增量生产的第一步,这样的架构的核心能力是什么?
- Sleeping second brother...
- BSN长话短说之十:如何保证NFT的安全
- C# 一行代码计算文件的MD5值 - CodePlus系列
猜你喜欢
![C# [字节数组]与[16进制字符串]互相转换 - CodePlus系列](/img/d2/dad88f53701c7cd7638bd4983cbb4b.png)
C# [字节数组]与[16进制字符串]互相转换 - CodePlus系列

Introduction of uniapp wechat applet components on demand

零基础入行软件测试必看,10年测试老鸟的良心建议(共15条)

Can you afford to buy a house in Beijing, Shanghai, Guangzhou and Shenzhen with an annual salary of 1million?

7-Zip boycotted? The callers have committed "three crimes": pseudo open source, unsafe, and the author is from Russia!

主流实时流处理计算框架Flink初体验

TC8:UDP_USER_INTERFACE_01-08

Prefabricated dishes usher in the "golden age", who can lead the next trillion market

The latest masterpiece of Alibaba, which took 182 days to produce 1015 pages of distributed full stack manual, is so delicious

Have you learned the necessary global exception handler for the project
随机推荐
Common penetration tools -goby
Project procurement management
php 实现抽奖功能
Introduction of uniapp wechat applet components on demand
年薪100万,在北上广深买的起房子吗?
Cortex M4 systick details
Continue to advance, and softcom power steadily promotes cloud intelligence strategy
Hardware midrange project
It is interesting to understand MMAP in this way!
SQL SERVER2014删除数据库失败,报错偏移量0x0000...
Sd-wan notes
直播管理项目
In the new database era, don't just learn Oracle and MySQL
树莓派4B系统搭建(超详细版)
Strange, why is the ArrayList initialization capacity size 10?
Tryhackme Christmas challenge 2021 advance of cyber 3-day1-idor vulnerability, insecure access control vulnerability
Does anyone know the logic of limit statement execution in Clickhouse? In the picture, the SQL above can be executed successfully
Initial experience of Flink, a mainstream real-time stream processing computing framework
High precision factorial
PHP 字符串与二进制相互转换