Last Updated on 2022-09-15 by Clay
題目
An integer array original
is transformed into a doubled array changed
by appending twice the value of every element in original
, and then randomly shuffling the resulting array.
Given an array changed
, return original
if changed
is a doubled array. If changed
is not a doubled array, return an empty array. The elements in original
may be returned in any order.
Example 1:
Input: changed = [1,3,4,2,6,8] Output: [1,3,4] Explanation: One possible original array could be [1,3,4]: - Twice the value of 1 is 1 * 2 = 2. - Twice the value of 3 is 3 * 2 = 6. - Twice the value of 4 is 4 * 2 = 8. Other original arrays could be [4,3,1] or [3,1,4].
Example 2:
Input: changed = [6,3,0,1] Output: [] Explanation: changed is not a doubled array.
Example 3:
Input: changed = [1] Output: [] Explanation: changed is not a doubled array.
Constraints:
1 <= changed.length <= 105
0 <= changed[i] <= 105
我們會得到一個陣列,我們要判斷陣列是否是『由一個原始的陣列加上乘以二之後的數值所組成』。如果是有這樣的原始陣列,則回傳;若無,則回傳空陣列。
解題思路
我是使用排序的方法。使用一個雜湊表,從最小的值開始依序判斷起。如果當前值沒有在雜湊表中,則意味著是原始陣列的數值,陣列後方的值必定有其兩倍的數值,是故將當前值乘以二放入雜湊表中,紀錄有一個這樣的數值...... 如果當前值有在雜湊表中,則將雜湊表中的該值次數減一(因為可能會有很多相同的兩倍值,所以是用數值的方式來儲存)。
最後,如果所有值都有對應的值,則該陣列為 Doubled Array,反之則否。
講解不清,以下還是直接看程式碼。
C++ 範例程式碼
class Solution {
public:
vector<int> findOriginalArray(vector<int>& changed) {
// Base case
if (changed.size() % 2 == 1) {
return {};
}
// Sort
sort(changed.begin(), changed.end());
// Init
vector<int> results;
unordered_map<int, int> isNeed;
for (int i=0; i<changed.size(); ++i) {
if (isNeed[changed[i]] == 0) {
++isNeed[changed[i]*2];
}
else {
--isNeed[changed[i]];
results.push_back(changed[i]/2);
}
}
return (results.size()==changed.size()/2)
? results
: vector<int>();
}
};