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 }
posted on 2016-06-17 19:21 zhuzhu2016 阅读(173) 评论(0) 编辑 收藏 举报