> 文档中心 > 「冲刺大厂基础3」

「冲刺大厂基础3」


冲刺大厂基础

1.给定一个整形数组,有一个数出现K次,其余的数出现了M次。求这个出现K次的数。

思路:记录每一个数的二进制位上的信息,申请一个长度为32的整形数组,如果当前数的二进制位上为1,相应整形数组位置上加1.

统计好之后,遍历数组,依次%M,如果余数等于K,则出现K的数,该位置上为1.要注意特判0。

public class Code08_KM {    public static int onlyTimes(int[] arr, int k, int m){ int[] t = new int[32]; for (int num : arr) {     for(int i = 0; i < 32; i++){  t[i] += ((num >> i) & 1);     } } int ans = 0; for(int i = 0; i < 32; i++){     if(t[i] % m != 0){  if(t[i] % m == k){      ans |= (1 << i);  }else{      return -1;  }     } } if(ans == 0){     int count = 0;     for (int num : arr) {  if(num == 0){      count ++;  }     }     if(count != k){  return -1;     } } return ans;    }}

2.反转单链表

思路:创建一个前置节点pre,创建一个后置节点next,然后每一次pre记录节点之前的信息,next记录节点的下一个节点的信息。

public static class Node{ public int value; public Node next; public Node(int data){     value = data; }    }    public static Node reverseLinkedList(Node head){ Node pre = null; Node next = null; while(head != null){     next = head.next;     head.next = pre;     pre = head;     head = next; } return pre;    }

3.反转双链表

思路:创建一个前置节点pre,创建一个后置节点next,然后每一次pre记录节点之前的信息,next记录节点的下一个节点的信息。

public static class DoubleNode{ public int value; public DoubleNode last; public DoubleNode next; public DoubleNode(int data){     value = data; }    }    public static DoubleNode reverseDoubleList(DoubleNode head){ DoubleNode pre = null; DoubleNode next = null; while(head != null){     next = head.next;     head.next = pre;     head.last = next;     pre = head;     head = next; } return pre;    }

4.给定一个链表,删除链表中指定的值

思路:首先找到不是指定值的节点,创建一个节点变量pre,创建一个节点变了cur,pre代表上一个节点,cur代表当前节点。cur进行while循环,寻找不是指定值的节点,如果发现不是指定值的节点,pre更新成当前节点。cur继续向后找,直到cur==null。

public class Code10_DeleteGivenValue {    public static class Node{ public int value; public Node next; public Node(int data){     value = data; }    }    public static Node removeValue(Node head, int num){ while(head != null){     if(head.value != num){  break;     }     head = head.next; } Node pre = head; Node cur = head; while(cur != null){     if(cur.value != num){  pre.next = cur.next;     }else{  pre = cur;     }     cur = cur.next; } return head;    }}

妊娠纹产品大全