This is the 22nd day of my participation in the August More Text Challenge
Related articles
LeetCode brush questions summary: LeetCode brush questions
1. Title Description
The third largest number
Given a non-empty array, return the third largest number in the array. If not, return the largest number in the array.
Start with simple questions to brush, exercise their thinking ability, for the interview preparation ~
Second, train of thought analysis
-
Look at the examples in the title, let’s clarify the idea ~
-
Example 1:
Input: [3, 2, 1] Output: 1 Explanation: The third largest number is 1.Copy the code
-
Example 2:
Input: [1, 2] Output: 2 Explanation: The third largest number does not exist, so return the largest number 2.Copy the code
-
Example 3:
Input: [2, 2, 3, 1] Output: 1 There are two numbers with a value of 2 in this example, and they are both second. The third largest number of all the different numbers is 1.Copy the code
-
First sort the array in descending order
-
Go to heavy
-
Check whether the array length is less than 3
-
Less than 3 returns the maximum, the first number
-
Instead, return the third largest number
AC code
-
Descending cracking method:
Class Solution {public int thirdMax(int[] nums) {// Int stream = array.stream (nums); Stream<Integer> integerStream = stream.boxed(); Integer[] integers = integerStream.toArray(Integer[]::new); List<Integer> result = new ArrayList<>(); // Integers. Sort (integers, collections.reverseOrder ()); for (int num : integers) { if (! result.contains(num)){ result.add(num); } } if (result.size()<3){ return result.get(0); } return result.get(2); }}Copy the code
- Personal feeling I this kind of solution in addition to change more trouble, train of thought or quite clear!
-
TreeSet:
class Solution { public int thirdMax(int[] nums) { TreeSet<Integer> set=new TreeSet(); for(int i:nums){ set.add(i); if(set.size()>3){ set.pollFirst(); } } if(set.size()<3){ return set.pollLast(); }else{ return set.pollFirst(); }}}Copy the code
- Insert all the elements into the TreeSet, and it automatically ranks them in ascending order
- During insertion, always maintain a length of 3, and if greater than 3, delete the smallest one
- Insert the completion of
- Return the last (maximum) if there is no third, otherwise return the first (always maintain that the first is the third-to-last).
Four,
- Thousands of ideas to solve the problem, whether this method is good, or whimsical solution, can solve is a good way! White cat black cat can catch mice cat is a good cat!
- Here are a few other LeetCode solutions for reference!
- Click jump: loop solution
- Click to jump to: JAVA line
I see a long way to go, I’m sure I’ll keep searching ~ ** If you think I’m a good blogger! Writing is not easy, please like, follow, comment and give encouragement to the blogger ~ Hahah