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

  • 相关阅读:
    Spark的精简安装步骤---陈楠心血总结
    关于Hadoop的集群环境下虚拟机采用NAT方式连不上网的解决
    size_t总结
    POJ 1852 Ants
    Digital Roots 1013
    1350. Primary Arithmetic
    Word Reversal
    POJ 2876 Cantoring Along
    逆序数的求法
    C++ 中cin
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4571250.html
Copyright © 2011-2022 走看看