# [学习报告]《LeetCode零基础指南》(第四讲) 数组

``````class Solution {
public:
int search(vector<int>& nums, int target) {
int index = -1;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == target) {
return i;
}
}
return index;
}
};
``````

``````class Solution {
public:
bool search(vector<int>& nums, int target) {

for (int i = 0; i < nums.size(); i++) {
if (target == nums[i]) {
return true;
}
}
return false;
}
};
``````

``````class Solution {
public:
int findMin(vector<int>& nums) {
int min = 5000;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] < min) {
min = nums[i];
}
}
return min;
}
``````

};

``````//第一种

class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {return n;}
int arr[1000] = {0};
arr[1] = 1,arr[2] = 2;
int i;
for (i=3; i <= n; i++) {
arr[i] = arr[i-1] + arr[i-2];
}
return arr[i-1];

}

};
//第二种
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {return n;}
int a = 1,b = 2;
int i;
for (i=3; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
};
``````

``````class Solution {
public:
int fib(int n) {
if(n < 2) return n;
int dp[2];
dp[0] = 0,dp[1] = 1;
for (int i = 2; i <= n; i++) {
int sum = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = sum;
}
return dp[1];
}
};

class Solution {
public:
int fib(int n) {
if(n < 2) return n;
return fib(n-1) + fib(n-2);
}
};

class Solution {
public:
int fib(int n) {
if(n < 2) return n;
int arr[31] = {0};
arr[1] = 1;
int i;
for ( i = 2; i<=n; ++i) {
arr[i] = arr[i-1] + arr[i-2];
}
return arr[i-1];
}
};
``````

``````class Solution {
public:
int tribonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1 || n == 2){
return 1;
}
int dp[3];

dp[0] = 0,dp[1] = 1,dp[2] = 1;
for (int i = 3; i <= n; i++) {
int sum = dp[0] + dp[1] + dp[2];
dp[0] = dp[1];
dp[1] = dp[2];
dp[2] = sum;
}
return dp[2];
}
};
``````

``````class Solution {
public:
int countKDifference(vector<int>& nums, int k) {
int cnt = 0;
for (int i = 0; i < nums.size(); i++) {
for (int j = i+1; j < nums.size(); j++) {
if (abs(nums[i] - nums[j]) == k) {
++cnt;
}
}
}
return cnt;
}
};
``````

``````class Solution {
public:
int game(vector<int>& guess, vector<int>& answer) {
int cnt = 0;
int i;
for (i = 0; i<3; i++) {
if(guess[i] == answer[i]) {++cnt;}
}
return cnt;
}
};
//三目我觉得好看点
class Solution {
public:
int game(vector<int>& guess, vector<int>& answer) {
int cnt = 0;
int i;
for (i = 0; i<3; i++) {
cnt += (guess[i] == answer[i]) ? 1 : 0;
}
return cnt;
}
};
``````

``````class Solution {
public:
int minCount(vector<int>& coins) {
int cnt = 0;
int i;
for (i = 0; i<coins.size(); i++) {
cnt += (coins[i] + 1) / 2;
}
return cnt;
}
};
``````

...全文
17 6 收藏 回复

5.9w+

2021-11-25 22:31