1、删除排序链表中的重复元素 II
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode cur=dummy;
while (cur.next!=null&&cur.next.next!=null){
if (cur.next.val==cur.next.next.val) {
ListNode temp=cur.next;
while (temp.next != null && temp.val == temp.next.val){
temp=temp.next;
}
cur.next=temp.next;
}else cur=cur.next;
}
return dummy.next;
}
2、移除链表元素
public ListNode removeElements(ListNode head, int val) {
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode cur=dummy;
while (cur.next!=null){
if (cur.next.val==val){
if (cur.next.next!=null) cur.next=cur.next.next;
else cur.next=null;
}else cur=cur.next;
}
return dummy.next;
}
3、找到小镇的法官
public int findJudge(int N, int[][] trust) {
Map<Integer, List<Integer>> map=new HashMap<>();
for (int[] ints : trust) {
if (!map.containsKey(ints[0])){
map.put(ints[0],new ArrayList<>());
}
map.get(ints[0]).add(ints[1]);
}
if (map.size()!=N-1) return -1;
for (int i = 1; i <= N; i++) {
if (!map.containsKey(i)){
for (int j = 1; j <= N; j++){
if (map.containsKey(j)){
List<Integer> list = map.get(j);
if (!list.contains(i)) return -1;
}
}
return i;
}
}
}
4、螺旋矩阵 III
public int[][] spiralMatrixIII(int R, int C, int r0, int c0) {
int total=R*C;
int[][] res=new int[total][2];
int len=1; //平移的长度
int index=0; //res的下标
int status=1; //四种状态,向左为1,向下为2,向右为3,向上为4
res[index][0]=r0;
res[index][1]=c0;
while (true){
for (int i = 0; i < len; i++) {
if (status==1) c0++;
else if (status==2) r0++;
else if (status==3) c0--;
else if (status==4) r0--;
if (r0<R&&c0<C&&r0>=0&&c0>=0&&index<total-1){ //判断是否在边界内
res[++index][0]=r0;
res[index][1]= c0;
}
if (index==total-1) return res;
}
if (status==2||status==4) len++;
if (status==4) status=1;
else status++;
}
}
5、二进制数转字符串
public String printBin(double num) {
StringBuilder sb=new StringBuilder();
sb.append("0.");
while (num!=0){
num*=2;
if (num>=1){
sb.append(1);
num-=1;
}else sb.append(0);
if (sb.length()>32) return "ERROR";
}
return sb.toString();
}