leetcode笔记:Contains Duplicate
2016-02-24 18:01
429 查看
一. 题目描述
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;反之返回false。
使用map来实现。遍历数组,每访问一个元素,看其是否在map中出现,如已出现过,则存在重复元素,返回
三. 示例代码
四. 小结
相关的题目有:Contains Duplicate II 和 Contains Duplicate III。
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;否则,返回
false。
这里提供两个方法:
先对数组进行排序,然后遍历数组,若出现两个相邻元素的值相同时,表明有重复元素,返回true;反之返回false。
使用map来实现。遍历数组,每访问一个元素,看其是否在map中出现,如已出现过,则存在重复元素,返回
true;如没有,则将元素加入到map中。
三. 示例代码
[code]// 方法一 class Solution { public: bool containsDuplicate(vector<int>& nums) { int n = nums.size(); if (n < 2) return false; sort(nums.begin(), nums.end()); for (int i = 1; i < n; ++i) if (nums[i] == nums[i - 1]) return true; return false; } };
[code]// 方法二 class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_map<int, int> numsMap; for (int i = 0; i < nums.size(); ++i) { if(numsMap.count(nums[i])){ return true; } numsMap.insert(pair<int, int>(nums[i], i)); } return false; } };
四. 小结
相关的题目有:Contains Duplicate II 和 Contains Duplicate III。
相关文章推荐
- if __name__ == '__main__':
- 如何解决failed to push some refs to git
- remove duplicated gene pair using awk
- bzoj 2434 [Noi2011]阿狸的打字机(fail树+离线处理+BIT)
- TIME_WAIT和CLOSE_WAIT
- Cornerstone的分支问题Merge dry run failed: working copy is too old
- RAID讲解
- 行为型模式11之4-Chain of Responsibility责任链模式例子理解
- org.hibernate.AssertionFailure: null id in com.base.program.entity.Program entry (don't flush the S
- Traits特性
- Your project contains errors, please fix them 。。。。
- table './pacific/custom_form' is marked as crashed and should be repaired
- 如何使用Gmail的别名功能?
- 如何使用Gmail的别名功能?
- HDU 1329 Hanoi Tower Troubles Again!(乱搞)
- 理解领域模型Domain Model
- AIX如何查看cpu个数
- GXT4.0 BorderLayoutContainer布局
- org.hibernate.AssertionFailure: null id in X.XX.XXX 原因及解决方案
- 五子棋AI算法第五篇-算杀