leetcode 442. Find All Duplicates in an Array | 442. 数组中重复的数据(位运算)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 442. Find All Duplicates in an Array | 442. 数组中重复的数据(位运算)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/find-all-duplicates-in-an-array/
題解
沒想出來,看了評論之后寫的,一語點醒。
思路就是,用num對應index的最高位表示是否出現過。
class Solution {public List<Integer> findDuplicates(int[] nums) {// when find a number i, flip the number at position i-1 to negative.// if the number at position i-1 is already negative, i is the number that occurs twice.ArrayList<Integer> list = new ArrayList<>();for (int i = 0; i < nums.length; i++) {int n = nums[i] & (0b01111111_11111111_11111111_11111111); // 最高位置0if (nums[n - 1] >>> 31 == 1) list.add(n);else nums[n - 1] |= (1 << 31);}return list;} }總結
以上是生活随笔為你收集整理的leetcode 442. Find All Duplicates in an Array | 442. 数组中重复的数据(位运算)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 954. Array
- 下一篇: leetcode 449. Serial