当前位置:网站首页>Leetcode records - sort -215, 347, 451, 75
Leetcode records - sort -215, 347, 451, 75
2022-07-01 16:57:00 【Slay__】
Leetcode Sorting related problems
215. No K Big element

Ideas
【 The final position 】 Find the second in the array K Big element , Related to sorting , Quick row can find the final position of an element in the sorted array every time ( And the left ones are smaller than this number , The ones on the right are larger than this number ), Learn from the idea of fast platoon , Optimize the search process with subscripts . Find the final position of one element at a time , If it is equal to K-1, Return this element to ; otherwise , If the element position is less than K, On its right side, the sub array is arranged quickly , Otherwise, line up quickly on the left .
Code
public int findKthLargest0(int[] nums, int k){
int left=0,right=nums.length-1;
while(left<right){
int mid=findIndex(nums,left,right); // Calling this method has sorted an element (mid It's about
if (mid==nums.length-k) return nums[mid]; // When mid Is the indicated subscript
else if (mid>nums.length-k) //mid Keep to the right , Go to the left
right=mid-1;
else
left=mid+1;
}
return nums[left];
}
public int findIndex(int[] nums,int begin,int end){
// The specified interval will begin The final position of the subscript element is found
int value=nums[begin];
int left=begin;
int right=end;
while(left<right){
while (left<right&&nums[right]>value)
right--;
while(left<right&&nums[left]<=value)
left++;
int temp=nums[left];
nums[left]=nums[right];
nums[right]=temp;
}
nums[begin]=nums[left];
nums[left]=value;
return left;
}
347. front K High frequency elements

Ideas
【 Element frequency order 】 Because the number of different elements is statistically sorted , Learn from bucket sorting , First count the number of elements (HashMap), Then put the same number of elements into a bucket ( A two-dimensional List), Elements output from more to less .
Code
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// Count the number of elements related or an attribute of an element —— use HashMap Key value pair
// Integer is not good as subscript , Just use the number as the subscript
// initialization HashMap
Map<Integer,Integer> map=new HashMap<>();// Keys represent numbers , Value represents the number of occurrences
for (int key:nums){
// Whether to include the key , If there is no initialization value 1
if (map.containsKey(key))
map.put(key,map.get(key)+1);
else
map.put(key,1);
}
// Put the same number of times in one List in
List<Integer>[] list=new ArrayList[nums.length+1];// In case they are all the same elements , At this time, it should be placed in the subscript nums.length It's about
for (int key:map.keySet()){
// For each key ——map.keySet() Get key collection
int value=map.get(key); // Get the value of this key , Indicates the number of key digits
if(list[value] == null){
list[value] = new ArrayList();
}
list[value].add(key); // Add it to the subscript of the corresponding number
}
// Reverse traversal List Output —— Because every child list I don't know how many , use int[] Ergodic , So again list Of addAll
List<Integer> output=new ArrayList<>();
for (int i = nums.length; i >0 && output.size()<k; i--) {
if (list[i]==null) continue;;
output.addAll(list[i]);
}
return output.stream().mapToInt(Integer::valueOf).toArray();
}
}
451. Sort the characters according to their frequency of occurrence

Ideas
【 Element frequency order 】 It is still the element frequency / Number related topics , And the scope is unknown , It's not about the following three elements , Learn from bucket sorting . Count the number of occurrences of each character , Then fill the bucket according to the number , Finally, take in reverse order .
Code
- And 347 Similar version
class Solution {
public String frequencySort(String s) {
Map<Character,Integer> map=new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i))==null) map.put(s.charAt(i),1);
else map.put(s.charAt(i),map.get(s.charAt(i))+1);
}
List<Character>[] list=new ArrayList[s.length()+1]; // Be careful
for (Character key:map.keySet()){
int value=map.get(key);
if (list[value]==null) list[value]=new ArrayList<>();
list[value].add(key);
}
List<Character> listOut=new ArrayList<>();
for (int i = list.length-1; i >0 ; i--) {
if (list[i]==null) continue; // Be careful
for (int j = 0; j < list[i].size(); j++) {
for (int k = 0; k < i; k++) {
listOut.add(list[i].get(j));
}
}
}
StringBuilder str = new StringBuilder();
for (Character character : listOut) {
// Yes ArrayList Traversal , Put a character in StringBuilder in
str.append(character);
}
return str.toString();
}
}
- List Save characters , Arrange according to the number of occurrences of each character from small to large , Finally, output in reverse order ( because List After the storage and weight removal , So take map Inside value, Output value Characters )
class Solution {
public String frequencySort(String s) {
Map<Character,Integer> map=new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i))==null) map.put(s.charAt(i),1);
else map.put(s.charAt(i),map.get(s.charAt(i))+1);
}
List<Character> listOut = new ArrayList<Character>(map.keySet());
Collections.sort(listOut, (a, b) -> map.get(b) - map.get(a));
StringBuilder str = new StringBuilder();
int size = listOut.size();
for (int i = 0; i < size; i++) {
char c = listOut.get(i);
int frequency = map.get(c);
for (int j = 0; j < frequency; j++) {
str.append(c);
}
}
return str.toString();
}
}
75. Color classification

Ideas
【3 The elements are sorted as a whole 】 If you use the method of occurrence frequency of multiple elements above , It's a little bit of a hassle . Three elements can be encountered 0 Move forward , encounter 2 Move back , encounter 1 unchanged . Use a double fingered needle ( One left Point to the sorted 0 Next person , One right Point to the sorted 2 Last ), At the same time, one more pointer i Traversal elements in turn , Meet the conditions and exchange with the corresponding pointer elements , Then take different steps . Special , If right Exchange ends ,i I don't know what elements are exchanged , Cannot step directly , Need to be handled again i, and right normal –.
Code
class Solution {
public void sortColors(int[] nums){
// The left and right pointers point to be placed 0 Location and waiting 2 The location of ;i Step through elements , See if you can exchange —— Thought is 0 Put it in the front ,2 Put it back
int left=0,right=nums.length-1,i=0;
while(i<=right){
// Be careful right It's all in the back 2, No need to deal with it ,right Can be any value at , Need to deal with , If 0, You need to change to the front
if (nums[i]==0)
swap(nums,i++,left++);
else if (nums[i]==2)
swap(nums,i,right--); // In the back is 2, It's possible to change the front 0/1/2, Need to be handled again
else
i++;
}
}
public void swap(int[] nums,int index1,int index2){
int temp=nums[index1];
nums[index1]=nums[index2];
nums[index2]=temp;
}
}
Skill summary
Sorting related ideas
① The position of an element / The watershed —— Refer to quick platoon ( Quick row put one element in the final position at a time , And the left side is small , Big on the right )
② The number of multiple elements is related —— Reference bucket sorting ( According to the number of elements, put them into the corresponding bucket )
③ The three elements are sorted —— One is put in front , One is put back , One does not deal with
Statistics of the number of elements HashMap
Map<Character,Integer> map=new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i))==null) map.put(s.charAt(i),1);
else map.put(s.charAt(i),map.get(s.charAt(i))+1);
}
List relevant ( A two-dimensional List,Integer Of List Turn array )
① When List Specify the length , And every element is stored List( A two-dimensional List):
List<Integer>[] list=new ArrayList[nums.length+1];// In case they are all the same elements , At this time, it should be placed in the subscript nums.length It's about
for (int key:map.keySet()){
// For each key ——map.keySet() Get key collection
int value=map.get(key); // Get the value of this key , Indicates the number of key digits
if(list[value] == null){
list[value] = new ArrayList();
}
list[value].add(key); // Add it to the subscript of the corresponding number
}
② A two-dimensional List Each of the List The first time you use it, you should declare :if (list[value]==null) list[value]=new ArrayList<>();
③ List Add many key value pairs addAll:output.addAll(list[i]); list[i] For one List.
④ Integer Type of List Turn array :return output.stream().mapToInt(Integer::valueOf).toArray();
map operation ( keyset 、 Key sequence 、 A key value +1)
① Get key collection :map.keySet(), Generally used to traverse each key:for (int key:map.keySet()){}, You can also directly create a List:List<Character> listOut = new ArrayList<Character>(map.keySet());.
② The value of a key +:map.put(s.charAt(i),map.get(s.charAt(i))+1);
③ according to map Inside value Sort key ( There is List in ):Collections.sort(listOut, (a, b) -> map.get(b) - map.get(a));
character List turn String(Character Arrays are the same thing )
StringBuilder str = new StringBuilder();
for (Character character : listOut) {
// Yes ArrayList Traversal , Put a character in StringBuilder in
str.append(character);
}
return str.toString();
边栏推荐
- redis -- 数据类型及操作
- Detailed explanation of activity life cycle and startup mode
- Why is the pkg/errors tripartite library more recommended for go language error handling?
- 拼接字符串,得到字典序最小的结果
- Transition technology from IPv4 to IPv6
- SystemVerilog structure (II)
- SQL question brushing 586 Customers with the most orders
- 阿里云、追一科技抢滩对话式AI
- How to use etcd to realize distributed /etc directory
- Redis6.0 new features
猜你喜欢
![[flask introduction series] cookies and session](/img/2e/d50e0a032c4ec48935cb5df206a29b.png)
[flask introduction series] cookies and session

模板引擎Velocity 基礎

SQL question brushing 584 Looking for user references

The amazing open source animation library is not only awesome, but also small

How to maintain the laptop battery

SystemVerilog structure (II)

Tutorial on the principle and application of database system (002) -- MySQL installation and configuration: MySQL software uninstallation (Windows Environment)

How to solve the keyboard key failure of notebook computer

免费抽奖 | 《阿巴豆》探索未来系列盲盒数字版权作品全网首发!

Mlperf training v2.0 list released, with the same GPU configuration, the performance of Baidu PaddlePaddle ranks first in the world
随机推荐
P2893 [USACO08FEB] Making the Grade G(dp&优先队列)
挖财学堂班主任给的证券账户安全吗?能开户吗?
C language input / output stream and file operation
智能运维实战:银行业务流程及单笔交易追踪
Research and investment strategy report of China's sodium sulfate industry (2022 Edition)
Today, at 14:00, 15 ICLR speakers from Hong Kong University, Beihang, Yale, Tsinghua University, Canada, etc. continue!
Babbitt | yuan universe daily must read: Naixue coin, Yuan universe paradise, virtual stock game Do you understand Naixue's tea's marketing campaign of "operation pull full"
软件工程导论——第六章——详细设计
VMware virtual machine failed during startup: VMware Workstation is incompatible with hyper-v
Bugku's file contains
博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”
PR basic clip operation / video export operation
China nylon 11 industry research and future forecast report (2022 Edition)
模板引擎Velocity 基礎
How to restore the system of Sony laptop
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
Determine whether the linked list is a palindrome linked list
数据库系统原理与应用教程(005)—— yum 离线安装 MySQL5.7(Linux 环境)
How to repair the laptop that cannot connect to the wireless network
String类