adding leetcode problems

This commit is contained in:
Jidong Xiao
2023-09-26 12:19:09 -04:00
parent b4a5e201ee
commit 6eb5eb10a1
3 changed files with 46 additions and 0 deletions

View File

@@ -223,3 +223,8 @@ The destructor is called implicitly when an automatically-allocated object goes
- Finish the definition of Vec::push_back. - Finish the definition of Vec::push_back.
- Write the Vec::resize function. - Write the Vec::resize function.
## 8.16 Leetcode Exercises
- [Leetcode problem 27: Remove Element](https://leetcode.com/problems/remove-element/). Solution: [p27_removeelement.cpp](../../leetcode/p27_removeelement.cpp)
- [Leetcode problem 263: Ugly Number](https://leetcode.com/problems/ugly-number/). Solution: [p263_uglynumber.cpp](../../leetcode/p263_uglynumber.cpp)

View File

@@ -0,0 +1,24 @@
class Solution {
public:
// use a non-type parameter as the template parameter list.
template <int F> // F represents factor, and it has to be constant
// reduce factor n, has to be reference, because we want to change n.
void reduceFactor(int& n){
while(n%F==0){
n = n/F;
}
}
bool isUgly(int n) {
// ugly number has to be a positive integer.
if(n<=0){
return false;
}
// reduce factor 2
reduceFactor<2>(n);
// reduce factor 3
reduceFactor<3>(n);
// reduce factor 5
reduceFactor<5>(n);
return (n==1);
}
};

View File

@@ -0,0 +1,17 @@
// note: using template here is completely unnecessary. this is just a demonstration of how to define a templated function.
class Solution {
public:
template <typename T>
T removeElement(vector<T>& nums, T val) {
int size = nums.size();
int j = 0;
for(int i=0;i<size;i++){
if(nums[i] != val){
nums[j] = nums[i];
j++;
}
}
return j;
}
};