leetcode 4.29
Posted wfplingyun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 4.29相关的知识,希望对你有一定的参考价值。
1、202快乐数
class Solution {
public:
int Sum(int n)
{
int res = 0;
while (n)
{
res+= (n % 10) * (n % 10);
n = n / 10;
}
return res;
}
bool isHappy(int n) {
unordered_map<int, int>m;
while (1)
{
int res = Sum(n);
if (res == 1)return true;
if (m.find(res) != m.end())return false;
m[res] = 1;
n = res;
}
}
};
2、1095
/**
* // This is the MountainArray‘s API interface.
* // You should not implement it, or speculate about its implementation
* class MountainArray {
* public:
* int get(int index);
* int length();
* };
*/
class Solution {
public:
int findtop(MountainArray& mountainArr)
{
int low = 0, high = mountainArr.length() - 1;
int val1 = 0,val2=0,val3=0;
while (high - low > 1)
{
int mid = (low + high) / 2;
val1 = mountainArr.get(mid);
val2 = mountainArr.get(mid - 1);
if(val1 < val2)
{
high = mid;
}
else
{
low = mid;
}
}
return (mountainArr.get(low) > mountainArr.get(high) ? low : high);
}
int findindex(MountainArray& mountainArr, int top,int target)
{
int low = 0, high = mountainArr.length() - 1, top1 = top;
int val=0,mid1=0, mid2 =0;
while (top - 1 > low)
{
mid1 = (low + top) / 2;
val = mountainArr.get(mid1);
if (val == target)
{
return mid1;
}
else if (val > target)
{
top = mid1;
}
else
{
low = mid1;
}
}
if (mountainArr.get(low) == target)return low;
if (mountainArr.get(top) == target)return top;
while (high-1 > top1)
{
mid2 = (high + top1) / 2;
val = mountainArr.get(mid2);
if (val== target)
{
return mid2;
}
else if (val > target)
{
top1 = mid2;
}
else
{
high = mid2;
}
}
if (mountainArr.get(high) == target)return high;
if (mountainArr.get(top1) == target)return top1;
return -1;
}
int findInMountainArray(int target, MountainArray& mountainArr) {
int top = findtop(mountainArr);
int res = findindex(mountainArr, top, target);
return res;
}
};
以上是关于leetcode 4.29的主要内容,如果未能解决你的问题,请参考以下文章
leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段