954. Array of Doubled Pairs
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.
Если задан entier tableau четной длины arr, return true, если можно переупорядочить arr так, чтобы arr[2 * i + 1] = 2 * arr[2 * i] для каждого 0 <= i < len(arr) / 2, или false в противном случае.
Exemple:
Input: arr = [3,1,3,6]
Output: false
C# solution
correspondant/originalusing System;
using System.Collections.Generic;
public class Solution {
public bool CanReorderDoubled(int[] arr) {
Dictionary<int, int> count = new Dictionary<int, int>();
foreach (int num in arr) {
if (count.ContainsKey(num)) {
count[num]++;
} else {
count[num] = 1;
}
}
Array.Sort(arr, (a, b) => Math.Abs(a).CompareTo(Math.Abs(b)));
foreach (int num in arr) {
if (count[num] == 0) continue;
if (!count.ContainsKey(2 * num) || count[2 * num] == 0) return false;
count[num]--;
count[2 * num]--;
}
return true;
}
}
C++ solution
brouillon automatique, à relire avant soumission#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public bool CanReorderDoubled(vector<int>& arr) {
unordered_map<int, int> count = new unordered_map<int, int>();
foreach (int num in arr) {
if (count.count(num)) {
count[num]++;
} else {
count[num] = 1;
}
}
Array.Sort(arr, (a, b) => abs(a).CompareTo(abs(b)));
foreach (int num in arr) {
if (count[num] == 0) continue;
if (!count.count(2 * num) || count[2 * num] == 0) return false;
count[num]--;
count[2 * num]--;
}
return true;
}
}
Java solution
brouillon automatique, à relire avant soumissionimport java.util.*;
import java.math.*;
// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
public boolean CanReorderDoubled(int[] arr) {
HashMap<int, int> count = new HashMap<int, int>();
foreach (int num in arr) {
if (count.containsKey(num)) {
count[num]++;
} else {
count[num] = 1;
}
}
Array.Sort(arr, (a, b) => Math.abs(a).CompareTo(Math.abs(b)));
foreach (int num in arr) {
if (count[num] == 0) continue;
if (!count.containsKey(2 * num) || count[2 * num] == 0) return false;
count[num]--;
count[2 * num]--;
}
return true;
}
}
JavaScript solution
correspondant/originalvar canReorderDoubled = function(arr) {
let count = new Map();
for (let num of arr) {
count.set(num, (count.get(num) || 0) + 1);
}
arr.sort((a, b) => Math.abs(a) - Math.abs(b));
for (let num of arr) {
if (count.get(num) === 0) continue;
if (count.get(num * 2) === 0) return false;
count.set(num, count.get(num) - 1);
count.set(num * 2, count.get(num * 2) - 1);
}
return true;
};
Go solution
correspondant/originalpackage main
import (
"sort"
)
func canReorderDoubled(arr []int) bool {
count := make(map[int]int)
for _, num := range arr {
count[num]++
}
sort.Slice(arr, func(i, j int) bool {
return abs(arr[i]) < abs(arr[j])
})
for _, num := range arr {
if count[num] == 0 {
continue
}
if count[2*num] == 0 {
return false
}
count[num]--
count[2*num]--
}
return true
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
Algorithm
Подсчитать частоту каждого elementа в tableauе.
Отсортировать tableau по абсолютным значениям elementов.
Для каждого elementа в отсортированном tableauе:
Проверить, можно ли сопоставить его с elementом, равным его удвоенному значению.
Уменьшить счетчик обоих elementов в словаре частот.
Если для каждого elementа можно find пару, вернуть true, иначе вернуть false.
😎
Vacancies for this task
offres actives with overlapping task tags are affichés.
Il n'y a pas encore d'offres actives.