leetcode.287 尋找重複數

287. 尋找重複數

給定一個包含 n + 1 個整數的數組 nums,其數字都在 1 到 之間(包括 1 和 n),可知至少存在一個重複的整數。假設只有一個重複的整數,找出這個重複的數。

示例 1:

輸入: [1,3,4,2,2]
輸出: 2

示例 2:

輸入: [3,1,3,4,2]
輸出: 3

說明:

  1. 不能更改原數組(假設數組是隻讀的)。
  2. 只能使用額外的 O(1) 的空間。
  3. 時間複雜度小於 O(n2) 。
  4. 數組中只有一個重複的數字,但它可能不止重複出現一次。

看到這個,首先想到的是另找一個數組存數字的個數,然後掃一遍O(n)

但一看要求是空間O(1), 時間O(n2)

所以要時間換空間

那就兩層循環,對於每一個數字掃後面有沒有和自己一樣的

#include <iostream>
#include <vector>

using namespace std;

int findDuplicate(vector<int>& nums) {
	int i, j;
	int len = nums.size();
	for(i = 0; i < len; i++){
		for(j = i + 1; j < len; j++){
			if(nums[j] == nums[i] and i != j){
				return nums[i];
			}
		}
	}
}

int main(){
	int n[] = {1,3,4,2,2};
	vector<int> nums(n, n + 5);
	int re = findDuplicate(nums);
	cout << re << endl;

}

 

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