深圳康福特戶外家具營銷型網(wǎng)站seo教程免費
前言
###我做這類文章一個重要的目的還是給正在學(xué)習(xí)的大家提供方向(例如想要掌握基礎(chǔ)用法,該刷哪些題?建議靈神的題單和代碼隨想錄)和記錄自己的學(xué)習(xí)過程,我的解析也不會做的非常詳細(xì),只會提供思路和一些關(guān)鍵點,力扣上的大佬們的題解質(zhì)量是非常非常高滴!!!
習(xí)題
1.鏈表隨機(jī)節(jié)點
題目鏈接:382. 鏈表隨機(jī)節(jié)點 - 力扣(LeetCode)
分析:數(shù)組存節(jié)點值,生成索引范圍內(nèi)的隨機(jī)數(shù)并返回該隨機(jī)數(shù)索引下的值
代碼:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {int[] arr = new int[10005];int count = 0;public Solution(ListNode head) {for(ListNode i = head;i!=null;i=i.next){arr[count++] = i.val;}}public int getRandom() {Random r = new Random();int number=r.nextInt(count);return arr[number];}
}/*** Your Solution object will be instantiated and called as such:* Solution obj = new Solution(head);* int param_1 = obj.getRandom();*/
2.扁平化多級雙向鏈表
題目鏈接:?430. 扁平化多級雙向鏈表 - 力扣(LeetCode)
題面:
分析:用數(shù)組遞歸存儲數(shù)值然后構(gòu)造雙向鏈表更加簡單些?
代碼:
/*
// Definition for a Node.
class Node {public int val;public Node prev;public Node next;public Node child;
};
*/class Solution {int[] arr = new int[1005];int count = 0;public Node flatten(Node head) {if(head==null)return head;for(Node i = head;i!=null;i=i.next){arr[count++] = i.val;if(i.child!=null){recursion(i.child);}}Node fhead = new Node();Node pre = fhead;for(int i = 0;i<count;i++){Node node = new Node(arr[i]);pre.next=node;node.prev=pre;pre = node;}// for(Node i = fhead.next;i!=null;i=i.next){// System.out.println(i.val);// }Node ans = fhead.next;ans.prev = null;return ans; }public void recursion(Node head){for(Node i = head;i!=null;i=i.next){arr[count++] = i.val;if(i.child!=null){recursion(i.child);}}}
}
后言
上面是數(shù)據(jù)結(jié)構(gòu)相關(guān)的習(xí)題,下一篇文章會將其他相關(guān)的習(xí)題。?