Leetcode:414. 第三大的数

题目描述:

在这里插入图片描述在这里插入图片描述

问题解答:

1.数组扩容法(此方法比较慢)

class Solution {
    public int thirdMax(int[] nums) {
       int[] newnums=new int[0];
       for(int i=0;i<nums.length;i++) {
    	   boolean flag=zhuangtai(nums[i],newnums);//定义状态
           if(flag) {//如果数字在新数组中不存在,就加进去。
        	   newnums=Arrays.copyOf(newnums, newnums.length+1);
        	   newnums[newnums.length-1]=nums[i];
           }
       }
       Arrays.sort(newnums);//对新数组排序
       if(newnums.length<3) {
    	   return newnums[newnums.length-1];
       }else {
    	   return newnums[newnums.length-3];
       }
        
    }
     //判断原来的数字是否在新数组中。
	private boolean zhuangtai(int num, int[] newnums) {
		// TODO Auto-generated method stub
		for(int i=0;i<newnums.length;i++) {
			if(num==newnums[i]) {
				return false;
			}
		}
		return true;
	}
}

set集合去重法1:

class Solution {
    public int thirdMax(int[] nums) {
        Integer max1 = null;
        Integer max2 = null;
        Integer max3 = null;
        Set<Integer> set=new HashSet <>();
         for(int i=0;i<nums.length;i++){
       set.add(nums[i]);  //存入Set无重复
    }
        for (Integer x : set) {
            /*
            if (x.equals(max1) || x.equals(max2) || x.equals(max3)) {
                continue;
            }*/
            if ((max1 == null) || x > max1) {
                max3 = max2;
                max2 = max1;
                max1 = x;
            }
            else if ((max2 == null) || x > max2) {
                max3 = max2;
                max2 = x;
            }
            else if ((max3 == null) || x > max3) {
                max3 = x;
            }
        }
        if (max3 == null) {
            return max1;
        }else {
            return max3;
        }
    }
}

set去重法2:

class Solution {
    public int thirdMax(int[] nums) {
        Set<Integer>set=new LinkedHashSet<Integer>(); //新建Set
    Arrays.sort(nums);//升序排列
    for(int i=0;i<nums.length;i++){
       set.add(nums[i]);  //存入Set无重复
    }
        
        int nums1[]=new int[set.size()];
        
        Iterator<Integer> it=set.iterator();
		while (it.hasNext()) {
		for(int i=0;i<set.size();i++){
            nums1[i]=it.next();
            }	
		} //读出输入到nums1[]数组中
        
        if(nums1.length<3){return nums1[nums1.length-1];}
        return nums1[nums1.length-3];   
    }
}

在这里插入图片描述在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42405666/article/details/89483322