【LeetCode-面試演算法經典-Java實現】【026-Remove Duplicates from Sorted Array(刪除排序數組中的重複元素)】,removeduplicates
【026-Remove Duplicates from Sorted Array(刪除排序數組中的重複元素)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
題目大意
給定一個排序的數組,將數組中的重複元素去掉,相同的只保留一個,並且返回數組新的元素個數,不要建立一個新的數組來儲存結果。在常量時間內解決這個問題
解題思路
從第二個元素開始處理,記為當前處理的元素,如果當前元素與他的前一個元素相同就刪除這個元素,如果不同就將它移動到正確的位置,返回最後數組元素人個數。
代碼實現
演算法實作類別
public class Solution { public int removeDuplicates(int[] A) { if (A.length == 0) { return 0; } int index = 0;//[0,index]只記錄數組中出現的按從小到大的唯一一個數,已經排好序了 int next = 1; // 演算法思想:找index之後的比A[index]大的數,如是找到就移動到A[index+1]處, // index移動到下一個位置,next移動到下一個位置,再找比A[index]大的數 while (next < A.length) { while (next < A.length && A[index] == A[next] ) { // 找不等於數組中最 next++; } if (next < A.length) { index++; A[index] = A[next]; next++; } } return index + 1; } private void swap(int[] a, int x, int y) { int tmp = a[x]; a[x] = a[y]; a[y] = tmp; }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47034985】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。