刷題-力扣-面試題 10.11. 峰與谷
阿新 • • 發佈:2022-03-10
題目連結
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/peaks-and-valleys-lcci
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
題目描述
在一個整數陣列中,“峰”是大於或等於相鄰整數的元素,相應地,“谷”是小於或等於相鄰整數的元素。例如,在陣列{5, 8, 4, 2, 3, 4, 6}中,{8, 6}是峰, {5, 2}是谷。現在給定一個整數陣列,將該陣列按峰與谷的交替順序排序。
示例:
輸入: [5, 3, 1, 2, 3]
輸出: [5, 1, 3, 2, 3]
提示:
- nums.length <= 10000
題目分析
- 根據題目描述,按照峰谷交替排序陣列
- 先對陣列按非遞增排序,在兩兩交換陣列元素
程式碼
class Solution { public: void wiggleSort(vector<int>& nums) { /* 5 3 1 2 3 5 3 3 2 1 5 3 3 1 2 */ int index = 1; int numsLen = nums.size(); std::sort(nums.begin(), nums.end(), compare); while (index < numsLen) { std::swap(nums[index], nums[index - 1]); index += 2; } return; } private: static bool compare(int a, int b) { return a > b; } };