剑指offer03--找出数组中重复的数字

剑指offer03:找出数组中重复的数字

  • 题目描述
    在这里插入图片描述
  • 思路解析:题目要求找出重复的数字,可以考虑java中的集合。Set集合内存储的数据不允许重复,考虑使用Set的两个子类,HashSetTreeSet。HashSet散列存放,无序;TreeSet:有序二叉树。结合题目,使用HashSet即可满足要求。将数组中的值依次通过add()方法存入HashSet中,如果添加成功,则不重复,如果添加失败,则说明HashSet中已存在该数,则该数重复,返回即可。
  • 代码实现
class Solution {
    
    
    public int findRepeatNumber(int[] nums) {
    
    
    	//创建HashSet
        Set<Integer> set = new HashSet<Integer>;
        //存放重复数
        int repeatNum = -1;
        //遍历数组,将值传入HashSet,并进行判断
        for(int num : nums){
    
    
			if(! set.add(num)){
    
    
				repeatNum = nums;
				break;
			}
		}
		return repeatNum;
    }
}

HashSet
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44809329/article/details/108836364