1. 程式人生 > 其它 >217.存在重複元素

217.存在重複元素

1.思路:將使用者輸入陣列先排序,然後從0開始遍歷至末尾,若存在相鄰兩個元素相同(arr【i】 == arr【i+1】),則說明存在相同元素;

2.演算法選擇:對時間複雜度的要求導致排序演算法不能選擇{“氣泡排序”、“選擇排序”、“插入排序”}這些時間複雜度是O(NlogN)的演算法;

      這裡選擇堆排序(heapSort)。【左神寫法】

      排好序後的遍歷檢查時間複雜度是O(N);

3.程式:

classSolution{ public:
voidswap(vector<int>&arr,intm,intn){ inttemp=arr[m]; arr[m]=arr[n]; arr[n]=temp; }

// 具體呼叫模組
//將陣列變成大根堆


voidheapInsert(vector<int>&arr,intindex){ intfather=(index-1)/2; while(arr[father]<arr[index]) { swap(arr,father,index); index=father; father=(index-1)/2; } } //從0開始向下,將剩餘根堆區的資料再次組成大根堆 voidheapify(vector<int>&arr,intindex,intheapSize){ intleft=2*index+1; while(left<heapSize){//如果有左孩子即如果還有孩子 intlargest=left+1<heapSize&&arr[left]<arr[left+1]?left+1:left;//二子選大 largest=arr[largest]>arr[index]?largest:index;//父和大子選大 if(largest==index)//若父即大,則不用換 break; swap(arr,largest,index);//走到這裡說明大子大於父,換二者 index=largest; left=index*2+1;
} } voidheapSort(vector<int>&arr){    //堆排序程式段 intlength=arr.size(); if(length<2) return; intheapSize=length;//第一個大根堆的大小 for(inti=0;i<length;i++) { heapInsert(arr,i);//第一次構建大根堆 } swap(arr,0,--heapSize);//確定陣列最大的資料在最後位置交換當前大根堆的首元素arr[0]和arr[heapSize] while(heapSize>0)//大根堆不為空(陣列還未排好序):大根堆數↓->排好序的陣列↑ { heapify(arr,0,heapSize);//第二次構建大根堆 swap(arr,0,--heapSize); } }
boolcontainsDuplicate(vector<int>&nums){    //演算法入口,整體思路先排序再查重 heapSort(nums);    //排序 boolsuccess; success=binaryfind(nums);    //查重 if(success==true) returntrue; elsereturnfalse; } boolbinaryfind(vector<int>&nums){    //查重程式段 for(inti=1;i<nums.size();i++) {//cout<<nums[i-1]<<nums[i]<<endl; if(nums[i]==nums[i-1])returntrue; }returnfalse; } }; 4.截圖 ①執行截圖

②leetcode截圖