zoukankan      html  css  js  c++  java
  • LeetCode26 Remove Duplicates from Sorted Array

    题目:

    Given a sorted array, 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 in place with constant memory.

    For example,
    Given input array nums = [1,1,2],

    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. (Easy)

     分析:

    这道题和下一个都是简单的双重指针倒腾数组元素的题。

    开始做的时候居然一直想swap,导致代码有点复杂,而且有一些情况开始没想到。

    当时去摩根面试的时候第一题就是这个,想想自己当时真是水的不行,怪不得被刷了...

    代码1:(swap的,要多一个cur记录是否重复,因为交换后会出现没法跟前一个比较。 不知道为什么脑子秀逗一直要swap...)

     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         if (nums.size() == 0) {
     5             return 0;
     6         }
     7         int p1 = 1, p2 = 1;
     8         int cur = nums[0];
     9         while (p1 != nums.size()) {
    10             if (nums[p1] != cur) {
    11                 cur = nums[p1];
    12                 if (p1 != p2) {
    13                     swap(nums[p1], nums[p2]);
    14                 }
    15                 p2++;
    16             }
    17             p1++;
    18         }
    19         return p2;
    20     }
    21 };

    代码2: (不要交换,就是两个指针,有一个维护所有不重复的元素,发现就拷过去,这多简单....)

     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         if (nums.size() == 0) {
     5             return 0;
     6         }
     7         int p1 = 1, p2 = 1;
     8         while (p1 != nums.size()) {
     9             if (nums[p1] != nums[p1 - 1]) {
    10                 nums[p2] = nums[p1];
    11                 p2++;
    12             }
    13             p1++;
    14         }
    15         return p2;
    16     }
    17 };

    代码3: (写成for循环虽然双重指针没那么明显,但是代码好看一些,以后还是这么写)

     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         if (nums.size() == 0) {
     5             return 0;
     6         }
     7         int p = 1;
     8         for (int i = 1; i < nums.size(); ++i) {
     9             if (nums[i] != nums[i - 1]) {
    10                 nums[p] = nums[i];
    11                 p++;
    12             }
    13         }
    14         return p;
    15     }
    16 };
     
  • 相关阅读:
    JS reduce方法的使用
    面试娱录
    sticky置顶功能影响了锚点定位
    postcss-px-to-viewport移动端自适应
    axios请求参数自动拼接到了地址那里
    ping 不通。无法访问目标主机
    JS前后台方法的相互调用
    SQL server2008 无法连接服务器
    Assembly.Load未能加载文件或程序集“”或它的某一个依赖项。系统找不到指定的文件
    JS判断IE和非IE
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5777901.html
Copyright © 2011-2022 走看看