LeetCode 75 Sort Colors(颜色排序)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 75 Sort Colors(颜色排序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
翻譯
給定一個包括紅色、白色、藍色這三個顏色對象的數組。對它們進行排序以使同樣的顏色變成相鄰的,其順序是紅色、白色、藍色。在這里,我們將使用數字0、1和2分別來代表紅色、白色和藍色。原文
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.分析
看到這道題。立刻就想到了range-for。可能這樣的方法有些投機吧。只是確實非常easy就實現了。
void sortColors(vector<int>& nums) {vector<int> v0, v1, v2; for (auto n : nums) {switch (n){case 0:v0.push_back(n);break;case 1:v1.push_back(1);break;case 2:v2.push_back(2);break;default:break;}}nums.erase(nums.begin(), nums.end());for (auto a0 : v0) {nums.push_back(a0);}for (auto a1 : v1) {nums.push_back(a1);}for (auto a2 : v2) {nums.push_back(a2);} }總結
以上是生活随笔為你收集整理的LeetCode 75 Sort Colors(颜色排序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js中常用的日期总结
- 下一篇: 大数据助力智慧城市建设