LEETCODE-Contains Duplicate

来源:互联网 发布:江西广电网络缴费 编辑:程序博客网 时间:2024/05/22 13:31

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
原创粉丝点击