?LeetCode刷題實戰(zhàn)26:刪除排序數(shù)組中的重復項
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎知識和業(yè)務邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?刪除排序數(shù)組中的重復項,我們先來看題面:
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ù)應該返回新的長度 2, 并且原數(shù)組 nums 的前兩個元素被修改為 1, 2。
你不需要考慮數(shù)組中超出新長度后面的元素。
示例?2:
給定 nums = [0,0,1,1,1,2,2,3,3,4],
函數(shù)應該返回新的長度 5, 并且原數(shù)組 nums 的前五個元素被修改為 0, 1, 2, 3, 4。
你不需要考慮數(shù)組中超出新長度后面的元素。
題解
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;
}
上期推文:
評論
圖片
表情
