输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if(input.empty() || k<=0 || k>input.size())
return {};
vector<int>data;
while(k--)
{
make_heap(input.begin(),input.end(),greater<int>());
data.push_back(input[0]);
pop_heap(input.begin(),input.end(),greater<int>());
input.pop_back();
}
return data;
}
};
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if(input.empty() || k<=0 || k>input.size())
return {};
sort(input.begin(),input.end());
vector<int>data(input.begin(),input.begin()+k);
return data;
}
};
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
return sorted(tinput)[:k] if k<=len(tinput) else []
# write code here
题目描述
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。你会不会被他忽悠住?(子向量的长度至少是1)
思路:动态规划
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array) {
if(array.empty())
return -1;
int array_max=array[0];
int max_data=array[0];
for(int i=1;i<array.size();++i)
{
array_max=max(array_max + array[i],array[i]);
max_data=max(max_data,array_max);
}
return max_data;
}
};
# -*- coding:utf-8 -*-
class Solution:
def FindGreatestSumOfSubArray(self, array):
if len(array)==0:
return -1
cur_max=data_max=array[0]
for i in array[1:]:
cur_max=max(cur_max+i,i)
data_max=max(data_max,cur_max)
# write code here
return data_max