巧妙算法:找出数组中消息的数字
生活随笔
收集整理的這篇文章主要介紹了
巧妙算法:找出数组中消息的数字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?題目:
在一個長度為n的數組里的所有數字都在0~n-1的范圍內。數組中某些數字是重復的,但是不知道有幾個數字重復了,也不知道每個數字重復了幾次。請找出數組中任意一個重復的數字。例如,如果輸入長度為7,的數組{2,3,1,0,2,5,3},那么對應的輸出是重復的數組2或者3。
class Solution {public List<Integer> findDisappearedNumbers(int[] nums) {for (int i = 0; i < nums.length; i++) {int newIndex = Math.abs(nums[i]) - 1; if (nums[newIndex] > 0) {nums[newIndex] *= -1;}}List<Integer> result = new LinkedList<Integer>();for (int i = 1; i <= nums.length; i++) { if (nums[i - 1] > 0) {result.add(i);}}return result;} }遍歷數組,把數組中的每個值當做下標賦值為-1,再遍歷一次,那個值不是-1的下標就是不存在的值
?
參考地址:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/solution/zhao-dao-suo-you-shu-zu-zhong-xiao-shi-de-shu-zi-2/
總結
以上是生活随笔為你收集整理的巧妙算法:找出数组中消息的数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有趣的0-1背包问题:分割等和子集
- 下一篇: golang中的strings.Inde