Skip to content

Commit dab33ab

Browse files
Merge pull request #2782 from Abe0770/main
Create 1675-minimize-deviation-in-array.cpp
2 parents ef15ee9 + 26c4a54 commit dab33ab

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

Diff for: c/0024-swap-nodes-in-pairs.c

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
Given a linked list, swap every two adjacent nodes and return its head.
3+
You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
4+
5+
Ex. Input: head = [1,2,3,4]
6+
Output: [2,1,4,3]
7+
8+
Time : O(N)
9+
Space : O(1)
10+
*/
11+
12+
/**
13+
* Definition for singly-linked list.
14+
* struct ListNode {
15+
* int val;
16+
* struct ListNode *next;
17+
* };
18+
*/
19+
struct ListNode* swapPairs(struct ListNode* head) {
20+
if (head == NULL || head->next == NULL)
21+
return head;
22+
23+
struct ListNode *new_head = head->next;
24+
struct ListNode *prev = NULL;
25+
26+
while (head != NULL && head->next != NULL) {
27+
struct ListNode *next_pair = head->next->next;
28+
struct ListNode *second = head->next;
29+
30+
if (prev != NULL)
31+
prev->next = second;
32+
33+
second->next = head;
34+
head->next = next_pair;
35+
36+
prev = head;
37+
head = next_pair;
38+
}
39+
40+
return new_head;
41+
}

Diff for: cpp/1675-minimize-deviation-in-array.cpp

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
You are given an array nums of n positive integers.
3+
4+
You can perform two types of operations on any element of the array any number of times:
5+
6+
If the element is even, divide it by 2.
7+
For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
8+
If the element is odd, multiply it by 2.
9+
For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].
10+
11+
The deviation of the array is the maximum difference between any two elements in the array.
12+
13+
Return the minimum deviation the array can have after performing some number of operations.
14+
Ex. Input: nums = [1,2,3,4]
15+
Output: 1
16+
Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
17+
18+
Time : O(N);
19+
Space : O(N);
20+
*/
21+
22+
class Solution {
23+
public:
24+
int minimumDeviation(vector<int>& nums) {
25+
priority_queue <int> pq;
26+
int minimum = INT_MAX;
27+
for(auto i : nums) {
28+
if(i & 1)
29+
i *= 2;
30+
minimum = min(minimum, i);
31+
pq.push(i);
32+
}
33+
int res = INT_MAX;
34+
while(pq.top() % 2 == 0) {
35+
int val = pq.top();
36+
res = min(res, val - minimum);
37+
minimum = min(val/2, minimum);
38+
pq.pop();
39+
pq.push(val/2);
40+
}
41+
return min(res, pq.top() - minimum);
42+
}
43+
};

0 commit comments

Comments
 (0)