Love丶FFC's Blog

LintCode_easy:包含重复值

2019-09-07 10:03:55
阅读:476   •   评论:3
标签:,

描述

给定一个整数数组,查找数组是否包含任何重复项。 如果数组中某个值至少出现两次,则函数应返回true,如果每个元素都是不同的,则返回false。

样例

样例 1:

输入:nums = [1, 1]
输出:True

样例 2:

输入:nums = [1, 2, 3]
输出:False

编程语言:Java

解题思想:

1.使用Hashset来判断第一个元素的情况。

2.使用枚举法来判断是否还存在一个元素相同。

3.使用boolean来判断结果。

时间复杂度:O(n^2)

IDE代码如下:

  1. package LintCode_Easy;
  2.  
  3. import java.util.HashSet;
  4.  
  5. public class _1320 {
  6.  
  7. public static void main(String[] args) {
  8. int[] nums = new int[] {1,2,3};
  9. HashSet<Integer> hashSet = new HashSet<Integer>();
  10. boolean containsDuplicate = false;
  11. for(int i=0;i<nums.length;i++)
  12. hashSet.add(nums[i]);
  13. for(int i=0;i<nums.length;i++)
  14. {
  15. if(hashSet.contains(nums[i])) //存在一个相同元素
  16. {
  17. for(int j=i+1;j<nums.length;j++) //从剩余元素中判断是否还存在一个相同元素
  18. {
  19. if(nums[j]==nums[i])
  20. {
  21. containsDuplicate=true;
  22. break;
  23. }
  24. }
  25. }
  26. }
  27. System.out.println(containsDuplicate);
  28. }
  29.  
  30. }

LintCode编辑器代码如下:

  1. public class Solution {
  2. public boolean containsDuplicate(int[] nums) {
  3. HashSet<Integer> hashSet = new HashSet<Integer>();
  4. boolean containsDuplicate = false;
  5. for(int i=0;i<nums.length;i++)
  6. hashSet.add(nums[i]);
  7. for(int i=0;i<nums.length;i++)
  8. {
  9. if(hashSet.contains(nums[i])) //存在一个相同元素
  10. {
  11. for(int j=i+1;j<nums.length;j++) //从剩余元素中判断是否还存在一个相同元素
  12. {
  13. if(nums[j]==nums[i])
  14. {
  15. containsDuplicate=true;
  16. break;
  17. }
  18. }
  19. }
  20. }
  21. return containsDuplicate;
  22. }
  23. }

评论板

共有 3 条评论

  1. FoorryNox

    The common marmoset, a New World monkey, has a primate specific cortex with approximately 40 Brodmann areas buy cialis online no prescription

  2. Preliaf

    You might try eye drops or even glasses with thick rims so you don t notice the shadow as much viagra patent expiration About 25 also used AIs about half of those taking them with tamoxifen and half without, for a median time period of between 2 and 3 years, according to the report

  3. LMHLJoAfr

    finpecia fast delivery overnight The International Society for Magnetic Resonance in Medicine and the Roger E

--------查看该分类下最新文章--------
^
新版博客正在完善中!域名:http://www.loveffc:8080,点击跳转,完全移植后将去除端口号。

Copyright © 2018 - 2021 FFC的小站 - 滇 ICP 备 18010780 号 - 1

- Powered by WordPress & AliYun · Theme by FFC -

- Environment by Windows & XAMPP · Designed by WebStorm & VSCode -

已运行:

访问量:456926