Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1.
Example 2:
Input: [1, 2] Output: 2 Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1] Output: 1 Explanation: Note that the third maximum here means the third maximum distinct number. Both numbers with value 2 are both considered as second maximum.
法1:使用快排中的“切分” O(NlgN)
public class Solution {
public int thirdMax(int[] nums)
{
HashSet<Integer> hashset=new HashSet<>(nums.length);
for(int n : nums)
hashset.add(n);
int[] arr=new int[hashset.size()];
int cnt=0;
for(int n :hashset)
arr[cnt++]=n;
int len=arr.length;
if(len<3)
{
int max=Integer.MIN_VALUE;
for(int i=0;i<len;i++)
max=Math.max(arr[i], max);
return max;
}
return findkth(arr, len-3, 0, len-1);
}
public int findkth(int[] nums,int k,int lo,int hi)
{
int kth=partition(nums, lo, hi);
int ele=nums[kth];
if(kth>k)
return findkth(nums, k, lo, kth);
else if(kth<k)
return findkth(nums, k, kth+1, hi);
else {
return ele;
}
}
public int partition(int[] nums,int lo,int hi)
{
if(lo==hi)
return lo;
int num=nums[lo];
int i=lo,j=hi+1;
while(true)
{
while(nums[++i]<num)
if(i==hi)
break;
while(nums[--j]>num)
if(j==lo)
break;
if(i>=j)
break;
swap(nums, i, j);
}
swap(nums, lo, j);
return j;
}
public static void swap(int[] arr ,int i, int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
法2 ,使用三个变量直接检索,摘自
https://discuss.leetcode.com/topic/62236/java-solution-in-0ms-run-time-o-n-and-space-o-1/15
public int thirdMax(int[] nums) {
long max = Long.MIN_VALUE, mid = max, min = max;
for (int ele : nums) {
if (ele > max) {
min = mid;
mid = max;
max = ele;
} else if (max > ele && ele > mid) {
min = mid;
mid = ele;
} else if (mid > ele && ele > min) {
min = ele;
}
}
return (int)(min != Long.MIN_VALUE ? min : max);
}