在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任一一個重複的數字。 例如,如果輸入長度爲7的數組[2,3,1,0,2,5,3],那麼對應的輸出是2或者3。存在不合法的輸入的話輸出-1
數據範圍:
進階:時間複雜度
,空間複雜度
示例1
說明:
2或3都是對的
struct Solution{
}
impl Solution {
fn new() -> Self {
Solution{}
}
/**
* 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規定的值即可
*
*
* @param numbers int整型一維數組
* @return int整型
*/
pub fn duplicate(&self, numbers: Vec<i32>) -> i32 {
// write code here
if numbers.len() == 0 {
return -1;
}
let mut nums:Vec<i32> = numbers;
for i in 0..nums.len() {
while nums[i] != i as i32 {
if nums[i] == nums[nums[i] as usize] {
return nums[i];
}
let tmp = nums[i] as usize;
nums.swap(tmp, i);
}
}
return -1;
}
}