217.存在重复元素

1.思路:将用户输入数组先排序,然后从0开始遍历至末尾,若存在相邻两个元素相同(arr【i】 == arr【i+1】),则说明存在相同元素;

2.算法选择:对时间复杂度的要求导致排序算法不能选择{“冒泡排序”、“选择排序”、“插入排序”}这些时间复杂度是O(NlogN)的算法;

      这里选择堆排序(heapSort)。

      排好序后的遍历检查时间复杂度是O(N);

3.程序:

class Solution {
public:

  void swap(vector<int>& arr,int m,int n){
    int temp = arr[m];  
    arr[m] = arr[n];
    arr[n] = temp;  
  }

// 具体调用模块
//将数组变成大根堆


  void heapInsert(vector<int>& arr,int index){
     int father = (index-1)/2;
     while(arr[father]<arr[index])
     {
        swap(arr,father,index);
        index = father;
        father = (index-1)/2;
     }
    
}
//从0开始向下,将剩余根堆区的数据再次组成大根堆 
void heapify(vector<int>& arr,int index,int heapSize){
     int left = 2*index+1;
     while(left<heapSize){ //如果有左孩子即如果还有孩子 
        int largest = 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;

      }
}
 
void heapSort(vector<int>& arr){    //堆排序程序段
    int length = arr.size();
    if(length<2)
      return;
    int heapSize=length;           //第一个大根堆的大小 
    for(int i=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); 
     }  

    bool containsDuplicate(vector<int>& nums) {      //算法入口,整体思路先排序再查重
    heapSort(nums);    //排序
    bool success;
    success = binaryfind(nums);    //查重
    if(success==true)
         return true;
    else return false;
    }
    bool binaryfind(vector<int>& nums){    //查重程序段
        for(int i=1;i<nums.size();i++)
        {   //cout<<nums[i-1]<<nums[i]<<endl;
            if(nums[i]==nums[i-1]) return true;
        }return false;
    }
};
4.截图
①运行截图

 

 ②leetcode截图

 

 

posted @   九月天9  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示