442. Find All Duplicates in an Array 找出數(shù)組中的重復(fù)元素

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
給定整數(shù)數(shù)組,元素a[i]滿足1 ≤ a[i] ≤ n,一些元素出現(xiàn)兩次、其余的出現(xiàn)一次,請(qǐng)?jiān)诰€性時(shí)間和就地完成的情況下找出出現(xiàn)兩次的元素。

Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]


思路:
參考 448. Find All Numbers Disappeared in an Array 找出數(shù)組中缺失的數(shù) 的做法,當(dāng)置第i個(gè)數(shù)num[i-1]時(shí),若元素已為負(fù)數(shù),則說明之前出現(xiàn)過。

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res=new ArrayList<>();
        for(int i=0;i<nums.length;i++){
            int val=Math.abs(nums[i])-1;
            if(nums[val]<0) res.add(val+1);
            nums[val]=-nums[val];
        }
        return res;
    }
}
class Solution(object):
    def findDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res=[]
        for i in range(len(nums)):
            val = abs(nums[i])-1
            if(nums[val]<0): res.extend([val+1])
            nums[val]=-nums[val]
        return res
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容