题目描述
输入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) {
vector<int> result;
int len = input.size();
if(k <= len){
sort(input.begin(),input.end());
for(int i = 0; i < k; i++){
result.push_back(input[i]);
}
}
return result;
}
};
解法二
class Solution {
public:
void swap(int &a, int &b){
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> result;
int len = input.size();
if (k <= len){
for (int i = 0; i < len; i++){
if (i < k){
int j = i;
while (j > 0 && input[j] > input[j / 2]){
swap(input[j], input[j / 2]);
j /= 2;
}
}
else{
if (input[i] >= input[0]){
continue;
}
else{
int j = 0;
input[j] = input[i];
while (j * 2 + 1 < k){
int maxIndex = j * 2 + 1;
if (j * 2 + 2 < k && input[j * 2 + 2] > input[maxIndex]){
maxIndex = j * 2 + 1;
}
if (input[j] > input[maxIndex]){
break;
}
else{
swap(input[j], input[maxIndex]);
j = maxIndex;
}
}
}
}
}
for (int i = k - 1; i > 0; i--){
swap(input[i], input[0]);
int j = 0;
while (j * 2 + 1 < i){
int maxIndex = j * 2 + 1;
if (j * 2 + 2 < k && input[j * 2 + 2] > input[maxIndex]){
maxIndex = j * 2 + 1;
}
if (input[j] > input[maxIndex]){
break;
}
else{
swap(input[j], input[maxIndex]);
j = maxIndex;
}
}
}
for (int i = 0; i < k; i++){
result.push_back(input[i]);
}
}
return result;
}
};
题目描述
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array) {
int sum = 0;
int result = array[0];
for(int i = 0; i < array.size(); i++){
sum += array[i];
if(sum > result){
result = sum;
}
if(sum < 0 ){
sum = 0;
}
}
return result;
}
};
题目描述
求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n)
{
int result = 0;
int temp = 1;
while(n/temp){
result += n/(temp*10)*temp;
if((n%(temp*10))/temp > 1){
result += temp;
}
if((n%(temp*10))/temp == 1){
result += n%temp + 1;
}
temp*=10;
}
return result;
}
};