当前位置:网站首页>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)。
边栏推荐
- 大佬们 有没有搞过sink分流写入clickhouse 或者其他数据库的操作。
- Po mode deep encapsulation
- The latest masterpiece of Alibaba, which took 182 days to produce 1015 pages of distributed full stack manual, is so delicious
- Ssh server rejects password, try again; Permitrootlogin yes invalid problem
- Introduction to expressions and operators in C language
- PHP code audit and File Inclusion Vulnerability
- Voice service notes
- Sleeping second brother...
- “中移链”国密引擎在BSN正式上线
- 年薪100万,在北上广深买的起房子吗?
猜你喜欢

Packetdrill script analysis guide

leetcode:111. 二叉树的最小深度

Live broadcast management project

Who has the vision to cross the cycle?

Win11账号被锁定无法登录怎么办?Win11账号被锁定无法登录

C one line code calculates the MD5 value of the file - codeplus series

睡了二哥。。。

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

云原生到底是什么?它会是未来发展的趋势吗?

这样理解mmap,挺有意思!
随机推荐
Prefabricated dishes usher in the "golden age", who can lead the next trillion market
年薪100万,在北上广深买的起房子吗?
Apple amplification! It's done so well
Meituan P4 carefully collated microservice system architecture design manual to see the world of microservice architecture
好高的佣金,《新程序员》合伙人计划来袭,人人皆可参与!
Is the securities account opened by Yixue school for individuals safe? Is there a routine
Daily mathematics serial 55: February 24
谁还在买“三只松鼠”们
SQL server2014 failed to delete the database, with an error offset of 0x0000
Some tools used in embedded development
Tryhackme Christmas challenge 2021 advance of cyber 3-day1-idor vulnerability, insecure access control vulnerability
哪个券商公司炒股开户佣金低又安全又可靠
Network partition notes
架构实战营 模块九:设计电商秒杀系统
历史上的今天:九十年代末的半导体大战;冯·诺依曼发表第一份草案;CBS 收购 CNET...
leetcode:111. Minimum depth of binary tree
High precision factorial
我喜欢两个男人。。。
Strange, why is the ArrayList initialization capacity size 10?
Is it safe to buy funds on the access letter?