排名:873 / 3304
第一题:有多少小于当前数字的数字
解题思路:双循环直接比较大小即可。
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int ans[] = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (i!=j && nums[i]>nums[j])ans[i]++;
}
}
return ans;
}
}
第二题:通过投票对团队排名
解题思路:一道排序的题目,一号选票只要有一张,后面的选票就无关紧要,一号选票相同时,才去看2号选票,以此类推。统计所有的1,2,3……选票,然后写个自定义排序即可。
class Solution {
public String rankTeams(String[] votes) {
List<HashMap<Character,Integer>> dict = new ArrayList<>();
for (int i = 0; i < votes[0].length(); i++) {
dict.add(new HashMap<>());
for (int j = 0; j < votes.length; j++) {
if (dict.get(i).containsKey(votes[j].charAt(i))){
dict.get(i).put(votes[j].charAt(i),dict.get(i).get(votes[j].charAt(i))+1);
}else {
dict.get(i).put(votes[j].charAt(i),1);
}
}
}
List<Character> collect = new ArrayList<>();
for (int i = 0; i < votes[0].length(); i++) {
collect.add(votes[0].charAt(i));
}
Collections.sort(collect, new Comparator<Character>() {
@Override
public int compare(Character o1, Character o2) {
for (int i = 0; i < dict.size(); i++) {
int a1 = dict.get(i).containsKey(o1)?dict.get(i).get(o1):0;
int a2 = dict.get(i).containsKey(o2)?dict.get(i).get(o2):0;
if (a1>a2)return -1;
else if (a1<a2) return 1;
}
return o1-o2;
}
});
StringBuilder ans = new StringBuilder();
for (int i = 0; i < collect.size(); i++) {
ans.append(collect.get(i));
}
return ans.toString();
}
}
第三题:二叉树中的列表
解题思路:题目给出一个链表,和一颗树。需要判断这个链表是否存在与子树中。枚举树中每一个与链表起始点的值相同的节点。利用dfs判断是否符合题意。
class Solution {
public boolean isSubPath(ListNode head, TreeNode root) {
if (head==null)return true;
if (root==null)return false;
if (head.val==root.val){
boolean flag = dfs5346(head.next,root.left)||dfs5346(head.next,root.right);
if (flag) return true;
}
return isSubPath(head,root.left)||isSubPath(head,root.right);
}
public boolean dfs5346(ListNode head, TreeNode root){
if (head==null)return true;
if (root==null)return false;
if (head.val==root.val){
return dfs5346(head.next,root.left)||dfs5346(head.next,root.right);
}
return false;
}
}