复杂链表的复制、字符串的排列、数组中出现次数超过一半的数字、最小的K个数、连续子数组的最大和
复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
C++代码
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead==NULL)
{
return NULL;
}
RandomListNode *current = pHead;
while(current!=NULL)
{
RandomListNode *clone = new RandomListNode(current->label);
clone->next = current->next;
current->next = clone;
current = clone->next;
}
current = pHead;
while(current!=NULL)
{
RandomListNode * clone = current->next;
if(current->random!=NULL)
{
clone->random = current->random->next;
}
current = clone->next;
}
current = pHead;
RandomListNode *CopyHead = pHead->next;
while(current->next!=NULL)
{
RandomListNode *clone = current->next;
current->next = clone->next;
current = clone;
}
return CopyHead;
}
};
参考链接,讲解很清楚
字符串的排列
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
C++代码
class Solution {
public:
vector<string> Permutation(string str)
{
vector<string>res;
if(str.size()==0)
{
return res;
}
sort(str.begin(),str.end());
do
{
res.push_back(str);
}while(next_permutation(str.begin(),str.end()));
return res;
}
};
数组中出现次数超过一半的数字
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
C++代码
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers)
{
sort(numbers.begin(),numbers.end());
int left = 0;
int right = numbers.size();
int middle = (left +right)/2;
int N = 0;
N = count(numbers.begin(),numbers.end(),numbers[middle]);
if(N>numbers.size()/2)
{
return numbers[middle];
}
else
{
return 0;
}
}
};
最小的K个数
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
C++代码
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k)
{
vector<int>res;
int len = input.size();
if(k>len)
{
return res;
}
sort(input.begin(),input.end());
res.insert(res.begin(),input.begin()+0,input.begin()+k);
return res;
}
};
连续子数组的最大和
题目描述
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
C++代码
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array)
{
int maxValue = INT_MIN;
int currentSum = 0;
int len = array.size();
for(int i = 0;i<len;i++)
{
currentSum = currentSum + array[i];
if(currentSum>maxValue)
{
maxValue = currentSum;
}
if(currentSum<0)
{
currentSum = 0;
}
}
return maxValue;
}
};