LeetCode:刪除排序數組中的重復項 (Remove Duplicates from Sorted Array)
阿新 • • 發佈:2018-12-02
排序數組 元素 span 索引 code etc dup return 進行
public class RemoveDuplicates { /** * 修改數組,使數組有序不重復。超出長度不考慮。 * @param 排序數組 * @return 數組不重復數的個數 */ public int removeDuplicates(int[] nums) { // 需要修改的元素的索引,從1開始 int index = 1; // 遍歷數組,次數是長度-1 for (int i = 0; i < nums.length - 1; i++) {// 對相鄰數進行異或,相同數異或值為0 if ((nums[i] ^ nums[i + 1]) != 0) { // 兩個數不同時,將後續數放到索引位置,同時索引自增 nums[index++] = nums[i + 1]; } } //直接返回索引,因為索引在改變元素後自增,等於有序數組長度 return index; } }
LeetCode:刪除排序數組中的重復項 (Remove Duplicates from Sorted Array)