85、第三大的数

首先想到的是排序然后进行相应的查找,那么复杂度肯定就满足不了了

	public static int thirdMax(int[] nums) {
		
		
		if(nums.length == 0){
			return 0;
		}
		
		if(nums.length == 1){
			return nums[0];
		}
		if(nums.length == 2){
			return Math.max(nums[0], nums[1]);
		}
		Arrays.sort(nums);
		
		int count = 0;
		for (int i = nums.length-1; i >= 0; i--) {
			int j = nums[i];
			if(i == 0){
				
			}else {
				if(nums[i] == nums[i-1]){
					continue;
				}else {
					count ++;
					if(count == 3){
						return nums[i];
					}
				}
			}
			
			
		}	
		System.out.println(nums[nums.length-1]);
		return nums[nums.length-1];
		
		
    }

重新思考,这种算法,可能对于大多数情况是适用的,但是试想一下如果数组里面包含了最小值呢,可能就会报错。。。

class Solution {
    public int thirdMax(int[] nums) {
        int max1 = Integer.MIN_VALUE;
		int max2 = Integer.MIN_VALUE;
		int max3 = Integer.MIN_VALUE;
		
		for (int i = 0; i < nums.length; i++) {
			int j = nums[i];
			if(max1 < j){
				 max3 = max2;
				 max2 = max1;
				 max1 = j;
				 
			}else if (j > max2 && j < max1) {
				
				max3 = max2;
				max2 = j;
				
			}else if (j < max2&& j > max3) {
				max3 = j;
				
			}
		}
		
		if(max3 == Integer.MIN_VALUE){
			return max1;
		}else {
			return max3;
		}
    }
}

转变一下思路,将最小值改成Long.MIN_VALUE即可

class Solution {
    public int thirdMax(int[] nums) {
        	long max1 = Long.MIN_VALUE;
		long max2 = Long.MIN_VALUE;
		long max3 = Long.MIN_VALUE;
		
		for (int i = 0; i < nums.length; i++) {
			int j = nums[i];
			if(max1 < j){
				 max3 = max2;
				 max2 = max1;
				 max1 = j;
				 
			}else if (j > max2 && j < max1) {
				
				max3 = max2;
				max2 = j;
				
			}else if (j < max2&& j > max3) {
				max3 = j;
				
			}
		}
		
		if(max3 == Long.MIN_VALUE){
			return (int) max1;
		}else {
			return (int) max3;
		}
    }
}

相关文章:

  • 2021-08-13
  • 2022-12-23
  • 2023-01-08
  • 2021-05-28
  • 2021-05-18
  • 2021-07-03
  • 2022-02-20
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-12
  • 2021-09-08
  • 2021-07-25
  • 2022-12-23
  • 2022-01-24
  • 2021-12-05
相关资源
相似解决方案