NC97 number of occurrences of the string TopK problem
Topic link
1
The string array is mapped, and then map.entrySet is placed into a list to sort the list.
2, code,
import java.util.*;
public class Solution {
/**
* return topK string
* @paramStrings String One-dimensional array strings *@paramK int The integer the k *@returnString String two-dimensional array */
public String[][] topKstrings (String[] strings, int k) {
// write code here
// write code here
if (k == 0) {
return new String[][]{};
} else {
String[][] res = new String[k][2];
TreeMap<String, Integer> treeMap = new TreeMap<>();
for (String str : strings) {
if (treeMap.containsKey(str)) {
treeMap.put(str, treeMap.get(str) + 1);
} else {
treeMap.put(str, 1);
}
}
ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(treeMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
if (o1.getValue() == o2.getValue()) {
if (o1.getKey().compareTo(o2.getKey()) < 0) {
return -1;
} else {
return 1; }}else {
returno2.getValue() - o1.getValue(); }}});for (int i = 0; i < k; i++) {
res[i][0] = list.get(i).getKey();
res[i][1] = String.valueOf(list.get(i).getValue());
}
returnres; }}}Copy the code
NC112 base conversion
Topic link
1
Common base processing, stack processing.
2, code,
import java.util.*;
public class Solution {
/** * base conversion *@paramM int Specifies the integer *@paramN int The base to which the integer is converted *@returnString The character string */
public String solve (int m, int n) {
// write code here
// write code here
boolean isNeg = false;
if (m < 0) {
m *= -1;
isNeg = true;
}
Stack<Integer> stack = new Stack<>();
while(m ! =0) {
stack.push(m % n);
m = m / n;
}
StringBuilder stringBuilder = new StringBuilder();
if (isNeg) {
stringBuilder.append("-");
}
while(! stack.isEmpty()) {int val = stack.pop();
if (val <= 9) {
stringBuilder.append(val);
} else {
stringBuilder.append((char)(val - 10 + 65)); }}returnstringBuilder.toString(); }}Copy the code
NC96 determines whether a linked list is palindromic
Topic link
1
A clumsy approach is to group the list of numbers and then use a double pointer to determine whether the array is palindrome
2, code,
import java.util.*;
/* * public class ListNode { * int val; * ListNode next = null; *} * /
public class Solution {
/ * * * *@paramHead ListNode class The head *@returnBool Bool */
private int getLen(ListNode node) {
int ret = 0;
ListNode temp = node;
while(temp ! =null) {
temp = temp.next;
ret++;
}
return ret;
}
public boolean isPail(ListNode head) {
// write code here
int len = getLen(head);
int[] arr = new int[len];
int index = 0;
ListNode temp = head;
while(temp ! =null) {
arr[index++] = temp.val;
temp = temp.next;
}
int l = 0;
int r = len - 1;
while (l <= r) {
if(arr[l] ! = arr[r]) {return false;
}
l++;
r--;
}
return true; }}Copy the code