題目要求:輸入一個有序的陣列,你需要原地刪除重複的元素,使得每個元素只能出現一次,返回去重後新陣列的長度
題目分析:原地刪除,即不可以建立新的輔助陣列,那麼需要在原陣列上修改解決。
這種一般採用雙指標技巧
即:如果是普通陣列,使用兩個指標slow和fast,fast負責網後遍歷,如果發現陣列元素不同,則把slow下標值對應的值替換為fast下標值對應的值,則在原陣列上完成儲存不重複值的操作,如果元素重複,則fast前進,而slow不動,則最終fast遍歷到末尾時,slow下標值對應的所有元素已經是不重複的有序陣列元素了
/** * 有序陣列或者連結串列,透過兩個指標方式去重資料,統計去重後陣列個數 */ public class ArraysTest { public static void main(String[] args) { int [] arrays = new int[7]; arrays[0] = 0; arrays[1] = 1; arrays[2] = 1; arrays[3] = 2; arrays[4] = 3; arrays[5] = 3; arrays[6] = 4; System.out.println(removeDuplicates(arrays)); } public static int removeDuplicates(int[] nums) { int slow = 0; int fast = 1; int length = nums.length; while (fast < length) { if(nums[slow] != nums[fast]){ slow++; nums[slow] = nums[fast]; } fast++; } return slow+1; } }
擴充套件問題,如果是有序連結串列呢,方式一樣處理,程式碼如下
/** * 有序陣列或者連結串列,透過兩個指標方式去重資料,統計去重後陣列個數 */ public class LinkedArraysTest { public static void main(String[] args) { LinkedList linkedList = new LinkedList(); linkedList.add(new Node(0)); linkedList.add(new Node(1)); linkedList.add(new Node(1)); linkedList.add(new Node(2)); linkedList.add(new Node(3)); linkedList.add(new Node(4)); linkedList.add(new Node(4)); Node head = removeDulplicated(linkedList); int count = 0; while (head !=null){ count++; head = head.next; } System.out.println(count); } public static Node removeDulplicated(LinkedList linkedList) { Node slow = linkedList.head; Node fast = linkedList.head.next; while (null != fast){ if(slow.data != fast.data){ slow.next = fast; slow = slow.next; } fast = fast.next; } slow.next =null; return linkedList.head; } public static class Node{ int data; Node next; public Node(int data) { this.data = data; } } public static class LinkedList{ Node head; public void add(Node node){ if(null == head){ head = node; }else{ Node current = head; while (current.next != null){ current = current.next; } current.next = node; } } } }