赞
踩
以下例题均来自LeetCode
后续不再另注来源
C++代码如下
int majorityElement(vector<int>& nums) { int len = nums.size(); if(len == 1) return nums[0]; else { int n = len - 1; return SubElement(nums, 0, n); } } int SubElement(vector<int>& nums, int low, int high) { vector<int> rst; if (low == high) return nums[low]; else { int mid = (low+high)/2; int left_element = SubElement(nums, low, mid); int right_element = SubElement(nums, mid+1, high); if(left_element == right_element) { return left_element; } else { int len = high-low+1; int left_count = 0;int right_count = 0; for(int i=low; i<len; ++i) { if(nums[i] == left_element) ++left_count; else if (nums[i] == right_element) ++ right_count; else continue; } return left_count > right_count ? left_element : right_element; } } }
此题用分治算法并不是最优算法
需要添加的伪代码如下
len_max_nums = len(max_nums);
rst = len + 1;
for i = 0 to len_max_nums - 1
2 target = max_nums[i]
for j = 0 to len
if (nums[j] == target)
left_cur = j
break
for j = len down to 0
if(nums[j] == target)
right_cur = j
break
rst = min(rst, right_cur - left_cur + 1)
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; else if(l2 == NULL) return l1; else { ListNode* rst = new ListNode(-1); ListNode* pre = rst; while(true) { if(l1->val >= l2->val) { pre->next = new ListNode(l2
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。