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 }
?
轉載于:https://www.cnblogs.com/zhuzhu2016/p/5594994.html
總結
以上是生活随笔為你收集整理的2016.6.17——Remove Duplicates from Sorted Array的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dex2jar java 1.8_dex
- 下一篇: eclipse中文乱码解决_解决git