tags: Weekly Contest

Weekly Contest 358

2815. Max Pair Sum in an Array (Easy)

限制 :

  • 2 <= nums.length <= 100
  • 1 <= nums[i] <= 10^4

Solution

注意題意是講說,數字的最大位一樣。這樣就可以很簡單解出來了。

時間複雜度:
O(n2)

空間複雜度:
O(1)

程式碼:

class Solution { public: bool isPair(int num1, int num2) { int max1 = 0, max2 = 0; while(num1>0) { max1 = max(max1, num1%10); num1/=10; } while(num2>0) { max2 = max(max2, num2%10); num2/=10; } if(max1==max2) return true; return false; } int maxSum(vector<int>& nums) { int result = -1; for(int i=0; i< nums.size() - 1;i++) { for(int j = i + 1; j < nums.size(); j++) { if(isPair(nums[i], nums[j]) == true) { result = max(result, nums[i] + nums[j]); } } } return result; } };

2816. Double a Number Represented as a Linked List (Medium)

限制 :

  • The number of nodes in the list is in the range [1, 104]
  • 0 <= Node.val <= 9
  • The input is generated such that the list represents a number that does not have leading zeros, except the number 0 itself.

Solution

這題不算難,因為只有乘2,所以最多只會進一位,這樣就是用兩個指標,這兩個指標都會在相鄰位置,在右邊的負責把裡面的數字相乘,如果要進位,會請左邊指標的值加一。

時間複雜度:
O(n)

空間複雜度:
O(1)

程式碼:

class Solution { public: ListNode* doubleIt(ListNode* head) { if (head->val >= 5) { ListNode* temp = new ListNode(); temp->next = head; head = temp; } else { head->val = head->val * 2; } ListNode* curr = head; ListNode* r = curr->next; while (r != nullptr) { if (r->val >= 5) { curr->val += 1; r->val = r->val * 2 - 10; } else { r->val *= 2; } r = r->next; curr = curr->next; } return head; } };

2817. Minimum Absolute Difference Between Elements With Constraint(Medium)

限制 :

  • 104

時間複雜度:
O()

空間複雜度:
O()

程式碼:

2818. Apply Operations to Maximize Score(Hard)

限制 :

  • 104

時間複雜度:
O()

空間複雜度:
O()

程式碼: