当前位置:网站首页>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();
边栏推荐
- SQL question brushing 1050 Actors and directors who have worked together at least three times
- Template Engine Velocity Foundation
- Rhcsa Road
- VMware 虚拟机启动时出现故障:VMware Workstation 与 Hyper-v 不兼容...
- 剑指 Offer II 105. 岛屿的最大面积
- 【C补充】【字符串】按日期排序显示一个月的日程
- How to restore the system with one click on Lenovo laptop
- 【Kotlin】高阶函数介绍
- Chinese diosgenin market forecast and investment strategy report (2022 Edition)
- Concatenate strings to get the result with the smallest dictionary order
猜你喜欢
How to use F1 to F12 correctly on laptop keyboard
Jojogan practice
Défaillance lors du démarrage de la machine virtuelle VMware: le poste de travail VMware n'est pas compatible avec hyper - V...
软件工程导论——第六章——详细设计
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"
Germany if was crowned with many awards. How strong is this pair of headphones? In depth evaluation of yinpo GTW 270 hybrid
PR basic clip operation / video export operation
GameFramework食用指南
Flux d'entrées / sorties et opérations de fichiers en langage C
游戏行业安全选择游戏盾,效果怎么样?
随机推荐
redis -- 数据类型及操作
Tutorial on the principle and application of database system (005) -- Yum offline installation of MySQL 5.7 (Linux Environment)
How to cancel automatic search and install device drivers for laptops
多线程并发之CountDownLatch阻塞等待
存在安全隐患 起亚召回部分K3新能源
机器学习11-聚类,孤立点判别
Internet News: "20220222" get together to get licenses; Many products of Jimi have been affirmed by consumers; Starbucks was fined for using expired ingredients in two stores
Basic use of MySQL
剑指 Offer II 015. 字符串中的所有变位词
P2592 [ZJOI2008]生日聚会(dp)
How to optimize repeated if err in go language= Nil template code?
Défaillance lors du démarrage de la machine virtuelle VMware: le poste de travail VMware n'est pas compatible avec hyper - V...
【flask入门系列】Cookie与Session
Computed property “xxx“ was assigned to but it has no setter.
Building blocks for domestic databases, stonedb integrated real-time HTAP database is officially open source!
VMware 虛擬機啟動時出現故障:VMware Workstation 與 Hyper-v 不兼容...
How to use F1 to F12 correctly on laptop keyboard
How to restore the system of Sony laptop
What are the differences between PHP and DW
Rhcsa Road