LeetCode:26. Remove Duplicates from Sorted Array(Easy)
阿新 • • 發佈:2017-12-29
代碼 重復 相等 sta http return eas length blog
1. 原題鏈接
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
2. 題目要求
給定一個已經排序的整數數組nums[ ],返回除去重復元素後的數組長度
註意:不能重新創建一個數組,空間復雜度為O(1)
3. 解題思路
使用指針j來遍歷數組,i用來計數。初始時,i指向nums[0],j指向nums[1]。
當nums[i] != nums[j]時,i++,且nums[i]=nums[j],從j所在元素位置繼續比較。
最後返回 i+1
4. 代碼實現
public class RemoveDuplicatesFromSortedArray26 { public static void main(String[] args) { int nums[] = {2, 2, 3, 4, 5, 5, 6}; System.out.println(removeDuplicates(nums)); } public static int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { //不相等時i++ i++; nums[i] = nums[j]; } } return i + 1; } }
運行結果:
LeetCode:26. Remove Duplicates from Sorted Array(Easy)