【剑指offer】3.数组中重复的数字

3.数组中重复的数字

题目描述

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

1.HashSet

使用hashSet去重 如果添加不成功说明出现了重复的元素 返回。

public int findRepeatNumber(int[] nums) {
        if(nums.length == 0 || nums.length <2){
            return -1;
        }
        Set<Integer> set = new HashSet<Integer>();
        int repeat = -1;
        for (int num : nums) {
            if (!set.add(num)) {
                repeat = num;
                break;
            }
        }
        return repeat;
    }

时间复杂度:O(n)

2.利用下标

将数组中的元素当成下标存储到数组中去,如果没有重复的就说明无重复数 否则有重复数字

   public boolean duplicate(int[] nums, int length, int[] duplication) {
        if (nums == null || length <= 0)
            return false;
        for (int i = 0; i < length; i++) {
            while (nums[i] != i) {
                if (nums[i] == nums[nums[i]]) {
                    duplication[0] = nums[i];
                    return true;
                }
                swap(nums, i, nums[i]);
            }
        }
        return false;
    }
    
    private void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }

时间复杂度:O(n)

posted @ 2020-03-25 18:28  qxlxi  阅读(107)  评论(0编辑  收藏  举报