[LeetCode]287. Find the Duplicate Number

来源:互联网 发布:数据口径 编辑:程序博客网 时间:2024/06/05 18:24

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:

  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.


思路:我想到两种一种是最简单的,遍历然后找此元素前边的所有元素是否有相同的,O(n2)的时间复杂度,还有一个种是用数组存每个数的次数,如果找到大于1次的就返回,O(n)的时间,但是费空间



O(n2):

public class Solution {    public int findDuplicate(int[] nums) {        for(int i=0;i<nums.length;i++){            for(int j=0;j<i;j++){                if(nums[i]==nums[j]){                    return nums[i];                }            }        }        return 0;    }    }


O(n):

public class Solution {    public int findDuplicate(int[] nums) {        int[] times=new int[nums.length+1];        for(int i=0;i<nums.length;i++){            times[nums[i]]++;            if(times[nums[i]]>1){                return nums[i];            }        }        return 0;            }}




0 0