Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions c/0024-swap-nodes-in-pairs.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
Given a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Ex. Input: head = [1,2,3,4]
Output: [2,1,4,3]

Time : O(N)
Space : O(1)
*/

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
if (head == NULL || head->next == NULL)
return head;

struct ListNode *new_head = head->next;
struct ListNode *prev = NULL;

while (head != NULL && head->next != NULL) {
struct ListNode *next_pair = head->next->next;
struct ListNode *second = head->next;

if (prev != NULL)
prev->next = second;

second->next = head;
head->next = next_pair;

prev = head;
head = next_pair;
}

return new_head;
}
43 changes: 43 additions & 0 deletions cpp/1675-minimize-deviation-in-array.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
You are given an array nums of n positive integers.

You can perform two types of operations on any element of the array any number of times:

If the element is even, divide it by 2.
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].
If the element is odd, multiply it by 2.
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].

The deviation of the array is the maximum difference between any two elements in the array.

Return the minimum deviation the array can have after performing some number of operations.
Ex. Input: nums = [1,2,3,4]
Output: 1
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.

Time : O(N);
Space : O(N);
*/

class Solution {
public:
int minimumDeviation(vector<int>& nums) {
priority_queue <int> pq;
int minimum = INT_MAX;
for(auto i : nums) {
if(i & 1)
i *= 2;
minimum = min(minimum, i);
pq.push(i);
}
int res = INT_MAX;
while(pq.top() % 2 == 0) {
int val = pq.top();
res = min(res, val - minimum);
minimum = min(val/2, minimum);
pq.pop();
pq.push(val/2);
}
return min(res, pq.top() - minimum);
}
};