39. 数组中出现次数超过一半的数字
题目
![](https://img-blog.csdnimg.cn/img_convert/5b27de38a68af141bcf5cc0c79e250ba.png)
题解
typedef struct HashNode{
int count;
int value;
UT_hash_handle hh;
}HashNode,*HashTable;
int majorityElement(int* nums, int numsSize){
HashTable ht = NULL;
HashNode * temp;
for(int i = 0;i < numsSize;i++){
HASH_FIND_INT(ht,&nums[i],temp);
if(temp != NULL){
temp->count++;
}else{
temp = (HashNode*)malloc(sizeof(HashNode));
temp->value = nums[i];
temp->count = 1;
HASH_ADD_INT(ht,value,temp);
}
}
for(temp = ht;temp!=NULL;temp = temp->hh.next){
if(temp->count > numsSize/2){
return temp->value;
}
}
return -1;
}
![](https://img-blog.csdnimg.cn/img_convert/2c82f9fa854617dc544c6b0dea986b41.png)
要点
用的是哈希表方法,对比哈希表的基础使用,本题中还多使用了一个哈希表的遍历。
HashNode * temp;
for(temp = 哈希表;temp != NULL;temp = temp->hh.next){//寻找next要使用哈表结构的句柄
//...
}
2139. 得到目标值的最少行动次数
题目
![](https://img-blog.csdnimg.cn/img_convert/681cf20092fd69cebcf06d6f559e4d70.png)
题解
int minMoves(int target, int maxDoubles){
//先使用乘2收益率是最高的。
int count = 0;
while(maxDoubles!=0 && target>1){
if(target % 2 == 0){
target = target / 2;
count++;
}else{
target = target / 2;
count += 2;
}
maxDoubles--;
}
count += target-1;
return count;
}
![](https://img-blog.csdnimg.cn/img_convert/dbb36713ef7420ef3cf740f3602e516f.png)
要点
1.使用贪心策略,乘2的收益总是比+1高,逆推回来。