Fork me on GitHub
image frame

Yangyang

Think. Learn. Create
Try to update hard.

Leetcode Study Day 5

Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.


Constraints:

1 <= prices.length <= 105
0 <= prices[i] <= 104

My Solution

Failed to find a solution by myself. So sad. I was trying to record the index and the value for every element and compare each element’s value and index. However, I failed to solve the situation that if the last element is the smallest one and we should ignore it.

“Buy low, sell high”

The idea is to find the minimum price (the day to buy) and the maximum profit (the day to sell) while iterating through the array of prices.

In ChatGPT’s code, there is no need to record the maximum value, the only two variables are the minimum value and the max profit. In the loop, we comapre the minimum value with the current value, find who is the smallest, and find the profit between them. Then we compare the profit with the max profit, find who is the largest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n <= 1) {
return 0; // If there are less than 2 days, you can't make a profit.
}

int minPrice = prices[0]; // Initialize the minimum price as the first day's price.
int maxProfit = 0; // Initialize the maximum profit as 0.

for (int i = 1; i < n; ++i) {
// Update the minimum price if a lower price is encountered.
minPrice = min(minPrice, prices[i]);

// Calculate the potential profit if you sell on the current day.
int potentialProfit = prices[i] - minPrice;

// Update the maximum profit if the potential profit is higher.
maxProfit = max(maxProfit, potentialProfit);
}

return maxProfit;
}
};

This is a smart idea and I am annoying that I didn’t think of it.

Leetcode Study Day 4

Rotate Array

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]


Constraints:

1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
0 <= k <= 105

My solution

My solution is actually very simple, I make a for loop to run k times. In this loop, I push all elements to a new array but make their index number plus 1. Then I replace the first element with the last element.
This method is not very efficient, and face the Time Limit Exceeded problem.

Reverse Method (Optimized):

Accroding to ChatGPT, the approach of reversing the array multiple times to achieve rotation is a well-known and clever technique that comes from a deeper understanding of how array rotations work. The code is very simple but it’s hard to relate reversation to this problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k %= n; // Handle cases where k is greater than n

if (k == 0) {
return; // No need to rotate if k is 0
}

reverse(nums.begin(), nums.end()); // Reverse the entire array
reverse(nums.begin(), nums.begin() + k); // Reverse the first k elements
reverse(nums.begin() + k, nums.end()); // Reverse the remaining elements
}
};

From this solution, I learn that if k, which is the rotation time can mod n, i.e., k % n = 0, there is no need to rotate the array. Then we only need to reverse the whole array first, then reverse the first k element first, then reverse the rest element first. This solution is related to math, and it’s very efficient.

Using Cyclic Replacements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k %= n; // Handle cases where k is greater than n

if (k == 0) {
return; // No need to rotate if k is 0
}

int count = 0; // Count of elements processed
int start = 0; // Start position for each cycle

while (count < n) {
int current = start;
int prev = nums[start];

do {
int next = (current + k) % n;
int temp = nums[next];
nums[next] = prev;
prev = temp;
current = next;
count++;
} while (start != current);

start++; // Move to the next cycle
}
}
};

I actually can’t get this idea, maybe leave it later…

Using Extra Array (Space-Optimized):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k %= n; // Handle cases where k is greater than n

if (k == 0) {
return; // No need to rotate if k is 0
}

vector<int> rotated(n); // Create an extra array

for (int i = 0; i < n; i++) {
rotated[(i + k) % n] = nums[i]; // Copy elements to their rotated positions
}

nums = rotated; // Copy the rotated array back to the original array
}
};

This solution is easier to understand. The main idea is to create a new array to store the rotated array. Then we copy the elements to their rotated positions. Finally, we copy the rotated array back to the original array. One thing that i need to understand is that we can use mod to get the rotated position of each element.

Leetcode Study Day 4

Majority Element

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Example 1:

Input: nums = [3,2,3]
Output: 3
Example 2:

Input: nums = [2,2,1,1,1,2,2]
Output: 2


Constraints:

n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109

My solution

Sort the array

We sort the array first in the non-decreasing order.

1
2
3
sort(nums.begin(), nums.end(), [](int & a, int & b){
return a < b ;
});

Count the number of each element

Then we loop the array and count how many times one value appears in the array. As the array is sorted already, we just need to check whether the current element is equal to the previous one. If they are equal, we plus 1 to the count, otherwise, we set the count to 0. We also set one variable to store the best count, and another variable to store the value that has the best count. During the loop, we update the best count and the value that has most count.

1
2
3
4
5
6
7
8
9
10
11
12
for (int i = 1; i < nums.size(); i++){
if (nums[i] == nums[i-1]){
count ++;
}
else{
count = 0;
}
if (count > best_count){
best_count = count;
return_val = nums[i];
}
}

Full code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 0;
int best_count = 0;
int return_val = 0;
sort(nums.begin(), nums.end(), [](int & a, int & b){
return a < b ;
});
if (nums.size() == 1){
return nums[0];
}
for (int i = 1; i < nums.size(); i++){
if (nums[i] == nums[i-1]){
count ++;
}
else{
count = 0;
}
if (count > best_count){
best_count = count;
return_val = nums[i];
}
}
return return_val;
}
};

Improved Solution

ChatGPT provides a better solution:

You can solve this problem in linear time and O(1) space using a well-known algorithm called “Boyer-Moore Majority Vote Algorithm.” This algorithm allows you to find the majority element in an array efficiently.

Here’s the algorithm in C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate = nums[0]; // Initialize the candidate as the first element
int count = 1; // Initialize the count of the candidate element

for (int i = 1; i < nums.size(); i++) {
if (count == 0) {
candidate = nums[i]; // Update the candidate if count becomes 0
count = 1;
} else if (nums[i] == candidate) {
count++; // Increment count if the current element is the same as the candidate
} else {
count--; // Decrement count if the current element is different from the candidate
}
}

return candidate; // The candidate is the majority element
}
};

Compare to my solution, this solution doesn’t sort the array, which save a lot of time. Also, it only have two variables. If the count is not equal to zero, which means the candidate variable is still the majority value. If the count is equal to zero, which means the candidate variable is not the majority value, we update the candidate variable to the current element, and set the count to 1.

Leetcode Study Day 3

Remove Duplicates from Sorted Array

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Custom Judge:

    The judge will test your solution with the following code:

    int[] nums = [...]; // Input array
    int[] expectedNums = [...]; // The expected answer with correct length

    int k = removeDuplicates(nums); // Calls your implementation

    assert k == expectedNums.length;
    for (int i = 0; i < k; i++) {
    assert nums[i] == expectedNums[i];
    }
    If all assertions pass, then your solution will be accepted.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    Example 1:

    Input: nums = [1,1,2]
    Output: 2, nums = [1,2,_]
    Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
    It does not matter what you leave beyond the returned k (hence they are underscores).
    Example 2:

    Input: nums = [0,0,1,1,1,2,2,3,3,4]
    Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
    Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
    It does not matter what you leave beyond the returned k (hence they are underscores).


    Constraints:

    1 <= nums.length <= 3 * 104
    -100 <= nums[i] <= 100
    nums is sorted in non-decreasing order.

    My solution

    My idea is loop the whole array from the second element to the end. If the element is equal to the previous one, we remove this element by using array.erase(nums.begin()+ i ). Then we return the size of the array.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class Solution {
    public:
    int removeDuplicates(vector<int>& nums) {
    for (int i = 1; i< nums.size(); i++){
    if (nums[i] == nums[i-1]){
    nums.erase(nums.begin()+i);
    i--;
    }
    if (i + 1 == nums.size())
    break;
    }
    int k = nums.size();
    return k;
    }
    };

    Remove Duplicates from Sorted Array II

    Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

1
2
3
4
5
6
7
8
9
10
11
12
Example 1:

Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:

Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3,_,_]
Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

The difference between this question and the first question is that we need to keep the first two elements of the duplicated elements.

My solution

Actually, my idea is similar with my solution of the first question. Compare the previous two elements, if the current one is equal to them, than wo remove them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
for (int i = 2; i < nums.size(); i++){
if (nums[i] == nums[i-1] && nums[i] == nums[i-2]){
nums.erase(nums.begin() + i);
i --;
}
if (i + 1 == nums.size()){
break;
}
}
return nums.size();
}
};

Improved solution

ChatGPT shows me an idea of using two pointers. It says my original solution cost O(n^2) time complexity because the function erase need to loop the whole array. Here is its improved solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if (n <= 2) {
return n;
}

int count = 1; // Initialize the count of the current element to 1
int j = 1; // The pointer for the next available position in the array

for (int i = 1; i < n; i++) {
if (nums[i] == nums[i - 1]) {
count++;
} else {
count = 1; // Reset the count for the new element
}

if (count <= 2) {
nums[j++] = nums[i]; // Copy the element to the next available position
}
}

return j; // j now holds the length of the modified array
}
};

If the count is smaller than 2, which means for now, there are less than 2 duplicated elements, we can copy the element which in position j to the current element. Other wise, we just skip the operation of duplicating the jth element to the current element because there are already two elements in the array. The improved solution’s time complexity is O(n).

However, for this solution, the last element in the array will not be changed. Althought it doesn’t matter because the question only want the first j elements of the array.

Leetcode Study Day 3

Remove Element

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.
Custom Judge:

The judge will test your solution with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).


Constraints:

0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100

My solution

We create a variable that can count how many duplicate elements appears in the array, k. And a new array to store the elements that are not equal to val. Then we loop the array nums, once the current element is not equal to val, k plus 1, and we store this element in the new array. After the loop, we replace the array nums with the new array, and return k.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
vector<int> outcome;
int k = 0;
for (int i = 0; i< nums.size(); i++){
if (nums[i] != val){
k ++;
outcome.push_back(nums[i]);
}
}
nums = outcome;
return k;
}
};

Leetcode Study Day 2

Merge Sorted Array

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].

Example 3:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
1
2
3
4
5
6
Constraints:
nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[j] <= 109

My solution

Merge two arrays

Firstly, we loop the first array nums1, if we find the element in this array is 0 and the index is larger than m, we replace it with the element in nums2 start from 0 to n, we call it j in my code.

1
2
3
4
5
6
7
int j = 0;
for (int i = 0; i < nums1.size(); i ++){
if (nums1[i] == 0 && n != 0 && i >= m){
nums1[i] = nums2[j];
j++;
}
}

If m is 0

If m is 0, which means the first array is empty, we just replace the first array with the second array.

1
2
3
if ( m == 0){
nums1 = nums2;
}

Sort the Array nums1

After merging the two arrays, we sort the array nums1 by using sort() function with lambda function.

1
2
3
sort (nums1.begin(), nums1.end(), [](int& a, int& b){
return a < b;
});

Full code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int j = 0;
for (int i = 0; i < nums1.size(); i ++){
if (nums1[i] == 0 && n != 0 && i >= m){
nums1[i] = nums2[j];
j++;
}
}
if ( m == 0){
nums1 = nums2;
}
sort (nums1.begin(), nums1.end(), [](int& a, int& b){
return a < b;
});
}
};

Time complexity

The for loop runs for nums1.size() iterations, which is m + n in the worst case.
Inside the loop, there is a conditional statement and potentially a nums1 assignment, both of which have constant time complexity.
The dominant factor in the time complexity is the sorting step at the end of the code:

Sorting nums1 using std::sort has a time complexity of O((m + n) * log(m + n)) in the worst case, where m + n is the total number of elements in nums1 and nums2.
So, the overall time complexity of the solution is O((m + n) * log(m + n)) due to the sorting step.

Improved solution run in O(m + n) time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m - 1;
int j = n - 1;
int k = m + n - 1;

while (i >= 0 && j >= 0) {
if (nums1[i] > nums2[j]) {
nums1[k--] = nums1[i--];
} else {
nums1[k--] = nums2[j--];
}
}

while (j >= 0) {
nums1[k--] = nums2[j--];
}
}
};

The key idea in this algorithm is to work from the end of the arrays towards the beginning, comparing elements and placing them in the correct position in nums1. This approach efficiently merges the two sorted arrays without the need for additional sorting

Leetcode Study Day 1

The K Weakest Rows in a Matrix

You are given an m x n binary matrix mat of 1’s (representing soldiers) and 0’s (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1’s will appear to the left of all the 0’s in each row.

A row i is weaker than a row j if one of the following is true:

The number of soldiers in row i is less than the number of soldiers in row j.
Both rows have the same number of soldiers and i < j.
Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Example 1:

Input: mat =
[[1,1,0,0,0],
[1,1,1,1,0],
[1,0,0,0,0],
[1,1,0,0,0],
[1,1,1,1,1]],
k = 3
Output: [2,0,3]
Explanation:
The number of soldiers in each row is:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
The rows ordered from weakest to strongest are [2,0,3,1,4].
Example 2:

Input: mat =
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]],
k = 2
Output: [0,2]
Explanation:
The number of soldiers in each row is:
- Row 0: 1
- Row 1: 4
- Row 2: 1
- Row 3: 1
The rows ordered from weakest to strongest are [0,2,3,1].
1
2
3
4
5
6
7
Constraints:

m == mat.length
n == mat[i].length
2 <= n, m <= 100
1 <= k <= m
matrix[i][j] is either 0 or 1.

My solution

Count soliders in the row

Since defining whether a row is weak, is based on the number of 1s in this row. So we can count how many 1s in a row first.

And since the 1s are always infront of the 0s, so once there is a 0 in the row, we can stop the loop. We then push the number of 1s and the index of the row into a vector.

1
2
3
4
5
6
7
8
9
10
11
vector<pair<int, int>> strength;
for (int i = 0; i < mat.size(); i++){
int count = 0;
for (int j =0; j < mat[i].size(); j++){
if (mat[i][j] == 1)
count ++;
else
break;
}
strength.push_back({count, i});
}

Sort the vector

After getting a vector of number of soliders and the index of each rows,
we then sort this vector based on this idea: we first consider the number of soliders and put the index of row with less soliders number in front of the row with more soliders number. If the number of soldiers are the same, then we compare the index of the row, and put the row with smaller index in front of the row with bigger index.

Explanation of this sort function: the first and the second parameters are the start and end position of the array, the third parameter is a lambda function, which is used to compare two elements in the array by the logic inside the function.

1
2
3
4
5
6
7
sort(strength.begin(), strength.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
if (a.first != b.first) {
return a.first < b.first;
} else {
return a.second < b.second;
}
});

Get the result

After sorting the vector, we can get the result by pushing the index of the row into a vector.

1
2
3
4
5
vector<int> result;
for (int i = 0; i < k; ++i) {
result.push_back(strength[i].second);
}
return result;

The full code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
vector<pair<int, int>> strength;
for (int i = 0; i < mat.size(); i++){
int count = 0;
for (int j =0; j < mat[i].size(); j++){
if (mat[i][j] == 1)
count ++;
else
break;
}
strength.push_back({count, i});
}
// Sort the strength vector based on the number of soldiers and then by row index
sort(strength.begin(), strength.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
if (a.first != b.first) {
return a.first < b.first;
} else {
return a.second < b.second;
}
});

// Extract the first k indices from the sorted strength vector
vector<int> result;
for (int i = 0; i < k; ++i) {
result.push_back(strength[i].second);
}
return result;
}
};

从零开始打造微信打卡小程序

微信小程序日历组件下载

网上找了许多关于打卡的微信小程序代码,感觉mehaotian的这段代码最容易理解,于是就想着在此之上改进。

打卡小程序预计架构

制作这个小程序的初衷是因为想要有个打卡app来记录每天做了什么事情,等时间一长看有几天做了这个事情会很有成就感。但我微信一搜感觉市面上的打卡app实在是过于冗余,我就想着能不能自己做个简洁的版本,这也是我第一次实实在在接触前端的东西,希望可以在这个项目中学习到前端的知识。这是基本的操作图:
UML class.png

最基本的打卡功能

我在原有的日历上增加了打卡按钮,现在界面是这样的:
Screenshot 2023-06-29 at 19.59.30.png
按下”打卡“按键后,会在当天打一个卡,并且不能重复打两次。源代码已经有了一个名为Slecetd的array,在这个array中的日期会在数字下有个红点,而我写了一个clockIn的方程使今天的日期加入到这个列表中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
clockIn() {
this.getWeek(new Date());
let selected = this.data.selected;
let canlender = this.data.canlender;
let { date, month, year } = canlender;
let addingDate = { date: year + "-" + month + "-" + date };
if(this.hasDuplicate(selected,addingDate)){
console.log("You can't add the same day twice!");
}
else{
selected.push(addingDate);
this.setData({
selected: selected
});
console.log(selected);
}
},

每日只能打一次卡

30/06/2023
移除了原本的“确定”按钮,该按钮的功能是折叠日历,但因为我们本质上就是一个打卡软件,所以就移除了这个功能。
“打卡”按钮改成了如果今天已经打卡过,则按钮会变灰,而且会显示“今天已经打过卡啦”。
Screenshot 2023-06-30 at 15.19.24.png

  • Copyrights © 2020-2024 Yangyang Cui

请我喝杯咖啡吧~

支付宝
微信