zoukankan      html  css  js  c++  java
  • leetcode之Contains 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.

    这道题和剑指OFFER上的面试题51很像,只是51题题目给出了数组长度以及数组中存储数字的范围。有点类似于桶排序。代码如下:

    public static boolean containsDuplicate(int[] nums) {
    		if (nums == null || nums.length <= 0) {
    			return false;
    		}
    		for (int i = 0; i < nums.length; i++) {
    			if (nums[i] < 0 || nums[i] > nums.length - 1) {
    				return false;
    			}
    		}
    		for (int i = 0; i < nums.length; i++) {
    			if (nums[i] < 0 || nums[i] > nums.length - 1) {
    				return false;
    			}
    			while (nums[i] != i) {
    				if (nums[i] == nums[nums[i]]) {
    					// int result = nums[i];
    					return true;
    				}
    				int temp = nums[i];
    				nums[i] = nums[temp];
    				nums[temp] = temp;
    			}
    		}
    		return false;
    	}
    

      而这道题可想到的有两种方法,首先是排序,对排序后的数组进行遍历,由于只是返回是否有重复元素,并不是返回重复的值,所以相邻元素比较即可

    还有一种方法是hashtable每次add之前判断是否已经存在,如果存在直接返回true然后结束,如果不contain就false

  • 相关阅读:
    Gulp使用入门操作---压缩JS
    Linux如何查看进程及如何杀死进程
    连不上GitHub,也ping不通,亲测解决方案
    idea一键生成mybatis工具
    idea逆向生成hibernate工程
    idea常用快捷键大全
    mysql日期函数
    数据库事务
    idea激活码
    oracle创建表前校验是否存在
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4571250.html
Copyright © 2011-2022 走看看