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

    Remove Duplicates from Sorted Array

    本题收获:

    1.“删除”数组中元素

    2.数组输出

      题目:

      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.

      题目的意思是:返回新的数组不重复的个数,且前输出这些数(但是不是要删除重复的数,重复的数赋值放在后面),如果输出的个数正确,但是输出的数组的数不对,也会报错

      思路:

      我的思路:不知道怎么删除数组

      leetcode:将后面的不重复的值前移,重复的值赋值为最后一个值,这样输出的前length个就为不重复的。

      代码

     1 class MyClass
     2 {
     3 public:
     4     int removeDuplicate(vector<int> nums)
     5     {
     6         int j = 0, n = 0;
     7         n = nums.size();
     8         for (size_t i = 1; i < n; i++)
     9         {
    10             if (nums[i - 1] == nums[i])
    11             {
    12                 j++;
    13             }
    14             else
    15                 nums[i - j] = nums[i];         //亮点所在    
    16         }
    17         return n-j;
    18     }

       我的测试代码:

      

     1 // Remove Duplicates from Sorted Array.cpp : 定义控制台应用程序的入口点。
     2 //
     3 
     4 #include "stdafx.h"
     5 #include "iostream"
     6 #include "vector"
     7 
     8 using namespace std;
     9 
    10 class MyClass
    11 {
    12 public:
    13     int removeDuplicate(vector<int> nums)
    14     {
    15         int j = 0, n = 0;
    16         n = nums.size();
    17         for (size_t i = 1; i < n; i++)
    18         {
    19             if (nums[i - 1] == nums[i])
    20             {
    21                 j++;
    22             }
    23             else
    24                 nums[i - j] = nums[i];
    25         }
    26         return n-j;
    27     }
    28 };
    29 
    30 
    31 int _tmain(int argc, _TCHAR* argv[])
    32 {
    33     vector<int> nums = { 1, 2, 2, 3, 4, 5, 5 };
    34     MyClass solution;
    35     vector<int> m;
    36     int n = 0;
    37     n = solution.removeDuplicate(nums);
    38     cout << n << endl;
    39     //测试输出数组用
    40     /*
    41     for (size_t i = 0; i < m.size();i++)
    42     {
    43         cout << m[i] << " ";
    44     }
    45     cout << endl;*/
    46     system("pause");
    47     return 0;
    48 }
  • 相关阅读:
    小贝_mysql 存储过程
    Codeforces Round #253 (Div. 1)-A,B
    rac环境改动spfile后遭遇ora-29250小例
    Linux学习笔记——例说makefile 索引博文
    《信息检索》课程论文撰写指南 及 分享加分说明
    git mirror的创建与使用
    一起talk GDB吧(第二回:GDB单步调试)
    nginx源代码分析--配置信息的继承&amp;合并
    EasyUI基础入门之Droppable(可投掷)
    自己动手写CPU之第七阶段(5)——流水线暂停机制的设计与实现
  • 原文地址:https://www.cnblogs.com/zhuzhu2016/p/5594994.html
Copyright © 2011-2022 走看看