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

原文地址:https://www.cnblogs.com/gracyandjohn/p/4571250.html