码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode[217]-Contains Duplicate

时间:2015-06-09 11:54:27      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:duplicate   element   return   value   return false   

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.


思路:先将数组排序,然后从第二个开始遍历,如果和前一个值相等,则返回true,终止;此方法时间复杂度为O(nlogn),空间复杂度为O(1)

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        int n = nums.size();
        int flag = false;

        std::sort(nums.begin(), nums.end());

        int i = 1;
        while(i < n){
            if(nums[i] == nums[i-1])
                return true;
            i++;
        }
        return flag;
    }

};

小记:自己做的时候,开始使用两个for循环遍历,结果超时了,后来使用自己写的快速排序,也超时了。最后使用了std::sort(nums.begin(), nums.end())自带的sort,结果成功了!不知道是快速排序哪里出了问题。



拓展:快速排序算法

void quickSort(vector<int> &nums,int low,int high){
    int i=low,j=high;
    if(i < j){
        int po = nums[low];
        while(i < j){
            while(nums[i]<nums[j] && po < nums[j]) j--;
            if(i<j){
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                i++;
            }
            while(nums[i]<nums[j] && nums[i] < po) i++;
            if(i<j){
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                j--;
            }
        }
        quickSort(nums,low,j-1);
        quickSort(nums,j+1,high);
    }
}

Leetcode[217]-Contains Duplicate

标签:duplicate   element   return   value   return false   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46424091

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!