Loading web-font TeX/Math/Italic
1 Star 0 Fork 0

wxyfmq123456/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
.github
.vscode
91
assets
backlog
collections
daily
problems
1.two-sum.en.md
1.two-sum.md
100.same-tree.md
1004.max-consecutive-ones-iii.md
101.symmetric-tree.md
1011.capacity-to-ship-packages-within-d-days-en.md
1011.capacity-to-ship-packages-within-d-days.md
1014.best-sightseeing-pair.md
1015.smallest-integer-divisible-by-k.md
1019.next-greater-node-in-linked-list.md
102.binary-tree-level-order-traversal.md
1020.number-of-enclaves.md
1023.camelcase-matching.md
103.binary-tree-zigzag-level-order-traversal.md
1031.maximum-sum-of-two-non-overlapping-subarrays.md
1032.stream-of-characters.md
104.maximum-depth-of-binary-tree.md
1043.partition-array-for-maximum-sum.md
108.convert-sorted-array-to-binary-search-tree.md
109.Convert-Sorted-List-to-Binary-Search-Tree.md
11.container-with-most-water.md
1104.path-in-zigzag-labelled-binary-tree.md
1128.number-of-equivalent-domino-pairs.md
1129.shortest-path-with-alternating-colors.md
113.path-sum-ii.md
1131.maximum-of-absolute-value-expression.md
1138.alphabet-board-path.md
1168.optimize-water-distribution-in-a-village-en.md
1168.optimize-water-distribution-in-a-village.md
1178.number-of-valid-words-for-each-puzzle.md
1186.maximum-subarray-sum-with-one-deletion.md
1203.sort-items-by-groups-respecting-dependencies.md
121.best-time-to-buy-and-sell-stock.md
1218.longest-arithmetic-subsequence-of-given-difference.md
122.best-time-to-buy-and-sell-stock-ii.md
1227.airplane-seat-assignment-probability.md
124.binary-tree-maximum-path-sum.md
125.valid-palindrome.md
1255.maximum-score-words-formed-by-letters.md
1260.shift-2d-grid.md
1261.find-elements-in-a-contaminated-binary-tree.md
1262.greatest-sum-divisible-by-three.md
128.longest-consecutive-sequence.md
129.sum-root-to-leaf-numbers.md
1297.maximum-number-of-occurrences-of-a-substring.md
130.surrounded-regions.md
131.palindrome-partitioning.md
1310.xor-queries-of-a-subarray.md
132.palindrome-partitioning-ii.md
1332.remove-palindromic-subsequences.md
1334.find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.md
136.single-number.md
1371.find-the-longest-substring-containing-vowels-in-even-counts.en.md
1371.find-the-longest-substring-containing-vowels-in-even-counts.md
1381.design-a-stack-with-increment-operation.md
139.word-break.md
140.word-break-ii.md
142.Linked-List-Cycle-II.md
1423.maximum-points-you-can-obtain-from-cards.md
1435.jump-game-iv.md
1438.longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md
144.binary-tree-preorder-traversal.md
1449.form-largest-integer-with-digits-that-add-up-to-target.md
145.binary-tree-postorder-traversal.md
146.lru-cache.md
147.insertion-sort-list.md
1494.parallel-courses-ii.md
15.3sum.md
150.evaluate-reverse-polish-notation.md
152.maximum-product-subarray.md
1521.find-a-value-of-a-mysterious-function-closest-to-target.md
1526.minimum-number-of-increments-on-subarrays-to-form-a-target-array.md
153.find-minimum-in-rotated-sorted-array.md
154.find-minimum-in-rotated-sorted-array-ii.md
155.min-stack.md
1558.minimum-numbers-of-function-calls-to-make-target-array.md
1574.shortest-subarray-to-be-removed-to-make-array-sorted.md
1589.maximum-sum-obtained-of-any-permutation.md
160.Intersection-of-Two-Linked-Lists.md
1631.path-with-minimum-effort.md
1649.create-sorted-array-through-instructions.md
1658.minimum-operations-to-reduce-x-to-zero.md
167.two-sum-ii-input-array-is-sorted.md
1671.minimum-number-of-removals-to-make-mountain-array.md
169.majority-element.md
1697.checking-existence-of-edge-length-limited-paths.md
17.Letter-Combinations-of-a-Phone-Number.md
1713.minimum-operations-to-make-a-subsequence.md
172.factorial-trailing-zeroes.md
1723.find-minimum-time-to-finish-all-jobs.md
1737.change-minimum-characters-to-satisfy-one-of-three-conditions.md
1787.make-the-xor-of-all-segments-equal-to-zero.md
1834.single-threaded-cpu.md
1835.find-xor-sum-of-all-pairs-bitwise-and.md
1871.jump-game-vii.md
1872.stone-game-viii.md
1899.merge-triplets-to-form-target-triplet.md
19.removeNthNodeFromEndofList.md
190.reverse-bits.md
1904.the-number-of-full-rounds-you-have-played.md
1906.minimum-absolute-difference-queries.md
191.number-of-1-bits.md
1970.last-day-where-you-can-still-cross.md
198.house-robber.en.md
198.house-robber.md
199.binary-tree-right-side-view.md
2.add-two-numbers.en.md
2.add-two-numbers.md
20.valid-parentheses.md
200.number-of-islands.md
2008.maximum-earnings-from-taxi.md
2009.minimum-number-of-operations-to-make-array-continuous.md
201.bitwise-and-of-numbers-range.md
2025.maximum-number-of-ways-to-partition-an-array.md
203.remove-linked-list-elements.md
2030.smallest-k-length-subsequence-with-occurrences-of-a-letter.md
206.reverse-linked-list.md
208.implement-trie-prefix-tree.md
209.minimum-size-subarray-sum.md
21.merge-two-sorted-lists.md
211.add-and-search-word-data-structure-design.md
212.word-search-ii.md
215.kth-largest-element-in-an-array.md
219.contains-duplicate-ii.md
22.generate-parentheses.md
220.contains-duplicate-iii.md
221.maximal-square.md
226.invert-binary-tree.md
227.basic-calculator-ii.md
229.majority-element-ii.md
23.merge-k-sorted-lists.md
230.kth-smallest-element-in-a-bst.md
232.implement-queue-using-stacks.md
236.lowest-common-ancestor-of-a-binary-tree.md
238.product-of-array-except-self.md
239.sliding-window-maximum.md
24.swapNodesInPairs.md
240.search-a-2-d-matrix-ii.md
25.reverse-nodes-in-k-groups-en.md
25.reverse-nodes-in-k-groups.md
26.remove-duplicates-from-sorted-array.md
263.ugly-number.md
279.perfect-squares.md
283.move-zeroes.md
29.divide-two-integers.md
295.find-median-from-data-stream.md
297.serialize-and-deserialize-binary-tree.md
3.longest-substring-without-repeating-characters.md
30.substring-with-concatenation-of-all-words.md
301.remove-invalid-parentheses.md
309.best-time-to-buy-and-sell-stock-with-cooldown.md
31.next-permutation.md
312.burst-balloons.md
32.longest-valid-parentheses.md
322.coin-change.md
328.odd-even-linked-list.md
33.search-in-rotated-sorted-array.md
330.patching-array.md
331.verify-preorder-serialization-of-a-binary-tree.md
334.increasing-triplet-subsequence.md
335.self-crossing.md
337.house-robber-iii.md
342.power-of-four.md
343.integer-break.md
349.intersection-of-two-arrays.md
365.water-and-jug-problem.md
371.sum-of-two-integers.md
378.kth-smallest-element-in-a-sorted-matrix.md
380.insert-delete-getrandom-o1.md
385.mini-parser.md
39.combination-sum.md
394.decode-string.md
4.median-of-two-sorted-arrays.md
40.combination-sum-ii.md
401.binary-watch.md
416.partition-equal-subset-sum.md
42.trapping-rain-water.en.md
42.trapping-rain-water.md
424.longest-repeating-character-replacement.md
437.path-sum-iii.md
438.find-all-anagrams-in-a-string.md
445.add-two-numbers-ii.md
454.4-Sum-ii.en.md
454.4-sum-ii.md
455.AssignCookies.md
456.132-pattern.md
457.circular-array-loop.md
46.permutations.md
460.lfu-cache.md
464.can-i-win.md
47.permutations-ii.md
470.implement-rand10-using-rand7.md
472.concatenated-words.md
473.matchsticks-to-square.md
474.ones-and-zeros-en.md
48.rotate-image.md
480.sliding-window-median.md
483.smallest-good-base.md
488.zuma-game.md
49.group-anagrams.md
493.reverse-pairs.md
494.target-sum.md
5.longest-palindromic-substring.md
50.pow-x-n.md
501.Find-Mode-in-Binary-Search-Tree-en.md
504.base-7.md
513.find-bottom-left-tree-value.md
516.longest-palindromic-subsequence.md
518.coin-change-2.md
52.N-Queens-II.md
525.contiguous-array.md
53.maximum-sum-subarray-cn.md
53.maximum-sum-subarray-en.md
547.friend-circles-en.md
547.friend-circles.md
55.jump-game.md
56.merge-intervals.md
560.subarray-sum-equals-k.en.md
560.subarray-sum-equals-k.md
5640.maximum-xor-with-an-element-from-array.md
57.insert-interval.md
575.distribute-candies.md
5775.minimum-skips-to-arrive-at-meeting-on-time.md
60.permutation-sequence.md
609.find-duplicate-file-in-system.md
61.Rotate-List.md
611.valid-triangle-number.md
62.unique-paths.md
63.unique-paths-ii.md
65.valid-number.md
66.plus-one.md
664.strange-printer.md
665.non-decreasing-array.md
673.number-of-longest-increasing-subsequence.md
679.24-game.md
686.repeated-string-match.md
714.best-time-to-buy-and-sell-stock-with-transaction-fee.md
715.range-module.md
718.maximum-length-of-repeated-subarray.md
721.accounts-merge.md
726.number-of-atoms.md
73.set-matrix-zeroes.md
735.asteroid-collision.md
75.sort-colors.md
754.reach-a-number.md
768.max-chunks-to-make-sorted-ii.md
78.subsets-en.md
78.subsets.md
785.is-graph-bipartite.md
79.word-search-en.md
79.word-search.md
790.domino-and-tromino-tiling.md
799.champagne-tower.md
80.remove-duplicates-from-sorted-array-ii.md
801.minimum-swaps-to-make-sequences-increasing.md
805.split-array-with-same-average.md
816.ambiguous-coordinates.md
820.short-encoding-of-words.md
821.shortest-distance-to-a-character.md
838.push-dominoes.md
839.similar-string-groups.md
84.largest-rectangle-in-histogram.md
85.maximal-rectangle.md
86.partition-list.md
87.scramble-string.md
873.length-of-longest-fibonacci-subsequence.md
874.walking-robot-simulation.md
875.koko-eating-bananas.md
877.stone-game.md
88.merge-sorted-array.md
886.possible-bipartition.md
887.super-egg-drop.md
895.maximum-frequency-stack.md
898.bitwise-ors-of-subarrays.md
90.subsets-ii-en.md
90.subsets-ii.md
900.rle-iterator.md
909.snakes-and-ladders.md
91.decode-ways.md
911.online-election.md
912.sort-an-array.md
92.reverse-linked-list-ii.md
932.beautiful-array.md
935.knight-dialer.md
94.binary-tree-inorder-traversal.md
947.most-stones-removed-with-same-row-or-column.md
95.unique-binary-search-trees-ii.md
959.regions-cut-by-slashes.md
96.unique-binary-search-trees.md
975.odd-even-jump.md
978.longest-turbulent-subarray.md
98.validate-binary-search-tree.md
987.vertical-order-traversal-of-a-binary-tree.md
995.minimum-number-of-k-consecutive-bit-flips.md
997.find-the-town-judge.md
Bus-Fare.md
Connected-Road-to-Destination.md
Increasing-Digits.md
Kth-Pair-Distance.md
Largest-Equivalent-Set-of-Pairs.md
Longest-Contiguously-Strictly-Increasing-Sublist-After-Deletion.md
Longest-Matrix-Path-Length.md
Minimum-Dropping-Path-Sum.md
Minimum-Light-Radius.md
Number-Stream-to-Intervals.md
Number-of-Substrings-with-Single-Character-Difference.md
Sort-String-by-Flipping.md
Ticket-Order.md
Triple-Inversion.md
binode-lcci.md
consecutive-wins.md
get-kth-magic-number-lcci.md
lcp20.meChtZ.md
lcp21.Za25hA.md
max-black-square-lcci.md
sub-sort-lcci.md
selected
templates
thinkings
.gitignore
CONTRIBUTING.en.md
CONTRIBUTING.md
Kapture 2020-08-19 at 11.37.36.gif
LICENSE.txt
README.en.md
README.md
SUMMARY.md
book.json
cover.jpg
donation.md
epilogue.md
introduction.md
package.json
thanksGiving.md
thanksGiving2.md
thanksGiving3.md
克隆/下载
26.remove-duplicates-from-sorted-array.md 4.25 KB
一键复制 编辑 原始数据 按行查看 历史
lucifer 提交于 4年前 . fix: $$ -> $

题目地址(26. 删除排序数组中的重复项)

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/description/

题目描述

给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。

示例  1:

给定数组 nums = [1,1,2],

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。

你不需要考虑数组中超出新长度后面的元素。 示例  2:

给定 nums = [0,0,1,1,1,2,2,3,3,4],

函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。

你不需要考虑数组中超出新长度后面的元素。

说明:

为什么返回数值是整数,但输出的答案是数组呢?

请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。

你可以想象内部操作如下:

// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

前置知识

公司

  • 阿里
  • 腾讯
  • 百度
  • 字节
  • bloomberg
  • facebook
  • microsoft

思路

使用快慢指针来记录遍历的坐标。

  • 开始时这两个指针都指向第一个数字

  • 如果两个指针指的数字相同,则快指针向前走一步

  • 如果不同,则两个指针都向前走一步

  • 当快指针走完整个数组后,慢指针当前的坐标加 1 就是数组中不同数字的个数

26.remove-duplicates-from-sorted-array

(图片来自: https://github.com/MisterBooo/LeetCodeAnimation)

实际上这就是双指针中的快慢指针。在这里快指针是读指针, 慢指针是写指针。从读写指针考虑, 我觉得更符合本质

关键点解析

  • 双指针

这道题如果不要求,O(n) 的时间复杂度, O(1) 的空间复杂度的话,会很简单。 但是这道题是要求的,这种题的思路一般都是采用双指针

  • 如果是数据是无序的,就不可以用这种方式了,从这里也可以看出排序在算法中的基础性和重要性。

  • 注意 nums 为空时的边界条件。

代码

  • 语言支持:JS,Python,C++

Javascript Code:

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
  const size = nums.length;
  if (size == 0) return 0;
  let slowP = 0;
  for (let fastP = 0; fastP < size; fastP++) {
    if (nums[fastP] !== nums[slowP]) {
      slowP++;
      nums[slowP] = nums[fastP];
    }
  }
  return slowP + 1;
};

Python Code:

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if nums:
            slow = 0
            for fast in range(1, len(nums)):
                if nums[fast] != nums[slow]:
                    slow += 1
                    nums[slow] = nums[fast]
            return slow + 1
        else:
            return 0

C++ Code:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.empty()) return 0;
        int fast,slow;
        fast=slow=0;
        while(fast!=nums.size()){
            if(nums[fast]==nums[slow]) fast++;
            else {
                slow++;
                nums[slow]=nums[fast];
                fast++;
            }
        }
        return slow+1;
    }
};

复杂度分析

  • 时间复杂度:O(N)
  • 空间复杂度:O(1)

更多题解可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 37K star 啦。

关注公众号力扣加加,努力用清晰直白的语言还原解题思路,并且有大量图解,手把手教你识别套路,高效刷题。

Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wxyfmq123456/leetcode.git
git@gitee.com:wxyfmq123456/leetcode.git
wxyfmq123456
leetcode
leetcode
master

搜索帮助