codingnote_devide
Created|Updated
|Word Count:734|Reading Time:3mins
题目:leetcode
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
求中位数实际上可以归结为分奇偶性的求第k小
class Solution { public: int getKthElement(const vector<int>& nums1, const vector<int>& nums2, int k) {
int m = nums1.size(); int n = nums2.size(); int index1 = 0, index2 = 0;
while (true) { if (index1 == m) { return nums2[index2 + k - 1]; } if (index2 == n) { return nums1[index1 + k - 1]; } if (k == 1) { return min(nums1[index1], nums2[index2]); }
int newIndex1 = min(index1 + k / 2 - 1, m - 1); int newIndex2 = min(index2 + k / 2 - 1, n - 1); int pivot1 = nums1[newIndex1]; int pivot2 = nums2[newIndex2]; if (pivot1 <= pivot2) { k -= newIndex1 - index1 + 1; index1 = newIndex1 + 1; } else { k -= newIndex2 - index2 + 1; index2 = newIndex2 + 1; } } }
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int totalLength = nums1.size() + nums2.size(); if (totalLength % 2 == 1) { return getKthElement(nums1, nums2, (totalLength + 1) / 2); } else { return (getKthElement(nums1, nums2, totalLength / 2) + getKthElement(nums1, nums2, totalLength / 2 + 1)) / 2.0; } } };
|
给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
link
法1:分治:result=max(left,right,cross)
法2:动态规划(线性),因为要求连续,所以定义f(i)为从i往前算出来的最大连续子数组
class Solution { public: int maxSubArray(vector<int>& nums) { int max_so_far = nums[0]; int current_max = nums[0];
for (size_t i = 1; i < nums.size(); i++) { current_max = max(nums[i], current_max + nums[i]); max_so_far = max(max_so_far, current_max); } return max_so_far; } };
|
(解决链表指针悬空,给一个dummy节点,返回的时候直接返回dummy的next)