題目:
找出數組中重複的數字。
在一個長度爲 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];
}
}