LEETCODE-Contains Duplicate

Contain Duplicate
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.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool containsDuplicate(vector<int> &nums) {
     sort(nums.begin(), nums.end());
        int len=nums.size();
        for(int i=1; i<len; i++){
            if(nums[i-1]==nums[i]){
                return true;
            }
        }
        return false;
    }

int main (){
     bool x;
     int b;
     vector<int> a;
     int n;
     cin >> n;
     for(int i = 0; i < n; i++){
        cin >> b;
        a.push_back(b);
     }
     x = containsDuplicate( a );
     cout << x;
    //~vector(a);
     vector<int>(a).swap(a);
}

这个程序运用了标准库类型vector,vector(可变大小数组。支持快速随机访问。在尾部之外的位置插入或删除元素可能很慢——c++ primer P292)是一种顺序容器。
1、首先要向vector对象中添加元素,利用push_back向其中添加元素;

//从标准输入中读取数据,将其作为vector对象的元素存储
string word;
vector<string> text;
while (cin >> word)
       text.push_back(word);//依次将string值放到v2尾端

2、在子函数bool containsDuplicate(vector &nums)中调用 sort 会重排输入序列中的元素;

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

3、在sort时使用begin和end 的成员
begin成员负责返回指向第一个元素的迭代器;
end成员负责返回指向容器“尾元素的下一个位置(one past the end)”的迭代器,该迭代器指示的是容器一个本不存在的“尾后(off the end)”元素;
——c++primer P95

b表示v的第一个元素,e表示v的尾元素的下一个位置;
auto b = v.begin(), e = v.end();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值