算法练习day19——190410(数组中重复的数字、替换空格、从尾到头打印链表)
1.數組中重復的數字
在一個長度為 n 的數組里的所有數字都在 0 到 n-1 的范圍內。數組中某些數字是重復的,但不知道有幾個數字是重復的,也不知道每個數字重復幾次。請找出數組中任意一個重復的數字。
要求復雜度為 O(N) + O(1)【時間復雜度 O(N),空間復雜度 O(1)】
1.1 分析
這種數組元素在 [0, n-1] 范圍內的問題,可以將值為 i 的元素調整到第 i 個位置上。
1.2 代碼實現
public class duplicateNum {public static void main(String[] args) {int[] arr= {2,3,1,0,2,5};int n=arr.length;System.out.println(duplicate(arr,n));}public static int duplicate(int[] nums,int len) {if(nums==null||len<=0)return -1;int res=-1;for(int i=0;i<len;i++) {while(nums[i]!=i) {//nums中i位置的值和i不等,需要交換或者看是否是重復的數字if(nums[i]==nums[nums[i]]) {res=nums[i];//只用找一個return res;}swap(nums,i,nums[i]);}}return -1;}public static void swap(int[] arr,int i,int j) {int temp=arr[i];arr[i]=arr[j];arr[j]=temp;} }2.替換空格
將一個字符串中的空格替換成 "%20"。
2.1 分析
在字符串尾部填充任意字符,使得字符串的長度等于替換之后的長度。
因為一個空格要替換成三個字符(%20) ,因此當遍歷到一個空格時,需要在尾部填充兩個任意字符。
令 P1 指向字符串原來的末尾位置,P2 指向字符串現在的末尾位置。
P1 和 P2從后向前遍歷,當 P1 遍歷到一個空格時,就需要令 P2 指向的位置依次填充 02%(注意是逆序的) ,否則就填充上 P1 指向字符的值。
從后向前遍是為了在改變 P2 所指向的內容時,不會影響到 P1 遍歷原來字符串的內容。
P1==P2時,結束。
2.1 代碼實現
public class ReplaceSpace {public static void main(String[] args) {String string="a b c";System.out.println(replaceSpace(string));}public static String replaceSpace(String str) {StringBuffer sb=new StringBuffer(str);//便于使用append()int p1=str.length()-1;for(int i=0;i<str.length();i++) if(sb.charAt(i)==' ')sb.append("##");//空格也行int p2=sb.length()-1;while(p1>=0&&p2>p1) {char c=sb.charAt(p1--);if(c==' ') {sb.setCharAt(p2--, '0');sb.setCharAt(p2--, '2');sb.setCharAt(p2--, '%');}elsesb.setCharAt(p2--, c); }return sb.toString();} }3.從尾到頭打印鏈表
輸入鏈表的第一個節點,從尾到頭反過來打印出每個結點的值。
3.1 分析1——使用棧
使用棧存儲遍歷過的節點值。
3.2 代碼實現1
package Qian10;import java.util.ArrayList; import java.util.Stack;public class PrintListReverse {static class Node{Node next;int value;public Node(int value) {this.value=value;}}public static void main(String[] args) {Node head=new Node(1);head.next=new Node(2);head.next.next=new Node(3);head.next.next.next=new Node(4);ArrayList<Integer> result=printListFromTailToHead1(head);for(int i=0;i<result.size();i++) System.out.print(result.get(i)+" "); }public static ArrayList<Integer> printListFromTailToHead1(Node head) {Stack<Integer> stack=new Stack<>();Node cur=head;ArrayList<Integer> res=new ArrayList<Integer>();while(cur!=null) {stack.push(cur.value);cur=cur.next;}while(!stack.isEmpty()) {res.add(stack.pop());}return res;} }3.3 分析2——使用遞歸
使用遞歸實現
當前節點不為空,繼續向后;為空,則將當前節點加入結果集,返回結果集。
使用addAll方法將返回的ArrayList中的所有數據全部加入到當前ArrayList中。
3.4 代碼實現2
public static ArrayList<Integer> printListFromTailToHead2(Node listNode) {ArrayList<Integer> ret = new ArrayList<>();if (listNode != null) {ret.addAll(printListFromTailToHead(listNode.next));ret.add(listNode.value);} return ret; }注:原博
ArrayList是一個實現可變長數組,繼承AbstractList類,實現所有的List接口,還實現了RandomAccess、Cloneable、Serializable接口。
add源代碼:
public boolean add(E e) {ensureCapacityInternal(size + 1);elementData[size++] = e;return true; }addAll源代碼:
//將Collection c內的數據插入ArrayList中 public boolean addAll(Collection<? extends E> c) {Object[] a = c.toArray(); int numNew = a.length;ensureCapacityInternal(size + numNew);// Increments modCountSystem.arraycopy(a, 0, elementData, size, numNew);size += numNew;return numNew != 0; }//將Collection c中的數據插入到ArrayList的指定位置 public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew); // Increments modCountint numMoved = size - index;if (numMoved > 0)System.arraycopy(elementData, index, elementData, index + numNew,numMoved);System.arraycopy(a, 0, elementData, index, numNew);size += numNew;return numNew != 0; }3.5 分析3——使用頭插法
利用鏈表頭插法為逆序的特點。
頭結點和第一個節點的區別:
- 頭結點是在頭插法中使用的一個額外節點,這個節點不存儲值;
- 第一個節點就是鏈表的第一個真正存儲值的節點。
前兩個節點的細節圖如下所示(類似于鏈表反轉):
3.6 代碼實現
public static ArrayList<Integer> printListFromTailToHead3(Node listNode) {// 頭插法構建逆序鏈表Node head = new Node(-1);while (listNode != null) {Node memo = listNode.next;listNode.next = head.next;head.next = listNode;listNode = memo;} // 構建 ArrayListArrayList<Integer> ret = new ArrayList<>();head = head.next;while (head != null) {ret.add(head.value);head = head.next;} return ret; }用反轉鏈表的思想實現:
public static ArrayList<Integer> printListFromTailToHead4(Node head) {Node cur=head;Node pre=null;Node next=null;while(cur!=null) {next=cur.next;cur.next=pre;pre=cur;cur=next;}ArrayList<Integer> ret = new ArrayList<>();while(pre!=null) {ret.add(pre.value);pre=pre.next;}return ret; }?
總結
以上是生活随笔為你收集整理的算法练习day19——190410(数组中重复的数字、替换空格、从尾到头打印链表)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法练习day18——190409(Ma
- 下一篇: ArrayList源码