?LeetCode刷題實(shí)戰(zhàn)26:刪除排序數(shù)組中的重復(fù)項(xiàng)
算法的重要性,我就不多說(shuō)了吧,想去大廠,就必須要經(jīng)過(guò)基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問(wèn)題叫做?刪除排序數(shù)組中的重復(fù)項(xiàng),我們先來(lái)看題面:
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
題意
樣例
示例?1:
給定數(shù)組 nums = [1,1,2],
函數(shù)應(yīng)該返回新的長(zhǎng)度 2, 并且原數(shù)組 nums 的前兩個(gè)元素被修改為 1, 2。
你不需要考慮數(shù)組中超出新長(zhǎng)度后面的元素。
示例?2:
給定 nums = [0,0,1,1,1,2,2,3,3,4],
函數(shù)應(yīng)該返回新的長(zhǎng)度 5, 并且原數(shù)組 nums 的前五個(gè)元素被修改為 0, 1, 2, 3, 4。
你不需要考慮數(shù)組中超出新長(zhǎng)度后面的元素。
題解
public?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++;
????????????nums[i] = nums[j];
????????}
????}
????return?i + 1;
}
上期推文:
