1.Challenge 1 description
Write a function solution that, given an integer N, returns the maximum possible value obtainable by deleting one ‘5’ digit from the decimal representation of N. It is guaranteed that N will contain at least one ‘5’ digit. Examples:
比如,N = 15958,返回1958.
#include
#include
using namespace std;
int main(){
int n;
cin >> n;
string s = to_string(n);
//cout<
int maxnum = INT_MIN;
for(int i = 0; i < s.size(); i++){
string temp = s;
if(temp[i] == '5'){
temp.erase(i,1);
maxnum = max(maxnum,atoi(temp.c_str()));
}
//cout<
}
cout<<maxnum;
}
2.Given A =[0,0,…, 0] of length 100,000, the function should return -1. Write an efficient algorithm for the following assumptions:
N is an integer within the range [1…100,000):
each element of array A is an integer within the range[-10,000…10,000].
using namespace std;
typedef long long ll;
ll sum[100100];
unordered_map<ll, int> cnt;
int solution(vector<int> &A) {
// write your code in C++ (C++14 (g++ 6.2.0))
sum[0] = A[0];
long long ans = 0;
cnt[sum[0]] ++;
if(sum[0] == 0) ans ++;
for(int i = 1; i < A.size(); i ++) {
sum[i] = sum[i-1] + A[i];
if(sum[i] == 0) {
ans += cnt[0] + 1;
cnt[0] ++;
continue;
}
ans += cnt[sum[i]];
cnt[sum[i]] ++;
}
if(ans > (ll)1e9) return -1;
return (int)ans;
}
3.等差数列
同力扣原题:
https://leetcode.cn/problems/arithmetic-slices/solution/
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& nums) {
int n = nums.size();
if (n == 1) {
return 0;
}
int d = nums[0] - nums[1], t = 0;
int ans = 0;
// 因为等差数列的长度至少为 3,所以可以从 i=2 开始枚举
for (int i = 2; i < n; ++i) {
if (nums[i - 1] - nums[i] == d) {
++t;
}
else {
d = nums[i - 1] - nums[i];
t = 0;
}
ans += t;
}
return ans;
}
};