adding leetcode problems
This commit is contained in:
@@ -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)
|
||||||
|
|||||||
24
leetcode/p263_uglynumber.cpp
Normal file
24
leetcode/p263_uglynumber.cpp
Normal 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);
|
||||||
|
}
|
||||||
|
};
|
||||||
17
leetcode/p27_removeelement.cpp
Normal file
17
leetcode/p27_removeelement.cpp
Normal 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;
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user