本文主要是介绍排序算法刷题【leetcode:04题,寻找两个正序数组的中位数。leetcode:219题,存在重复的元素 】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码如下所示:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;/* leetcode04题:寻找两个正序数组的中位数 */
class Solution {
public:double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {int L1 = nums1.size(), L2 = nums2.size(), p1 = 0, p2 = 0, p3 = 0;vector<int> nums(L1 + L2);while (p1 < L1 || p2 < L2){if (p1 == L1 || p2 != L2 && (nums1[p1] >= nums2[p2])){nums[p3++] = nums2[p2++];}else {nums[p3++] = nums1[p1++];}}p1 = (L1 + L2) / 2, p2 = (L1 + L2) / 2;if ((L1 + L2) % 2 == 0) p1--;double ret = (nums[p1] + nums[p2]) / 2.0;return ret;}
};void test()
{vector<int> v1, v2;v1.push_back(1);v1.push_back(3);v2.push_back(2);Solution s1;double ret = s1.findMedianSortedArrays(v1, v2);cout << "ret:" << ret;
}/* leetcode219题:存在重复的元素 */
class Solution {
public:bool containsNearbyDuplicate(vector<int>& nums, int k) {vector<int> index;for (int i = 0; i < nums.size(); i++) index.push_back(i);sort(index.begin(), index.end(), [&](int i, int j)->bool {if (nums[i] != nums[j]) return nums[i] < nums[j]; //数组元素不相等,按照数组元素的大小排序return i < j; }); //数组元素相等按照数组下标从小到达排序for (int i = 1; i < nums.size(); i++) //排序之后,数组相邻元素肯定挨边{if (nums[index[i - 1]] != nums[index[i]]) continue;if (index[i] - index[i - 1] <= k) return true;}return false;}
};void test()
{vector<int> arry;for (int i = 1; i < 4; i++) arry.push_back(i);for (int i = 1; i < 4; i++) arry.push_back(i);Solution s1;s1.containsNearbyDuplicate(arry, 2);}int main()
{test();return 0;
}
这篇关于排序算法刷题【leetcode:04题,寻找两个正序数组的中位数。leetcode:219题,存在重复的元素 】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!