劍指Offer之數組中重複數字

題目:

  找出數組中重複的數字。

  在一個長度爲 n 的數組 nums 裏的所有數字都在 0~n-1 的範圍內。數組中某些數字是重複的,但不知道有幾個數字重複了,也不知道每個數字重複了幾次。請找出數組中任意一個重複的數字。

示例 1:

輸入: [2, 3, 1, 0, 2, 5, 3] 
輸出:2 或 3

題解:

  方法一:

  利用字典Dictionary,遍歷數組,在將數字存入字典前,判斷字典中是否存在該數字,若存在,便返回該數字即可,不存在存入數組即可。

public class Solution 
{
    public int FindRepeatNumber(int[] nums) 
    {
        Dictionary<int,int> res = new Dictionary<int,int>();
        int index = 0;
        int result = -1;
        while(index < nums.Length)
        {
            if(res.ContainsKey(nums[index]))
            {
                result = nums[index];
                break;
            }
            else
            {
                res.Add(nums[index],1);
                index++;
            }
        }
        return result;
    }
}

  方法二:

  所以將數組排序後,相鄰兩值比較即可。

public class Solution 
{
    public int FindRepeatNumber(int[] nums) 
    {
        Array.Sort(nums);
        int index = 0;
        while(index < nums.Length)
        {
            if(nums[index] == nums[index+1])
            {
                break;
            }
            else
            {
                index++;
            }
        }
        return nums[index];
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章