2024-08-28: In go, given an array nums of integers starting at 1 and of length n, define a function greaterCount(arr, val) that returns the number of elements in the array arr that are greater than val.
Perform n operations according to the following rules to assign the elements in nums to two arrays arr1 and arr2:
1. The first operation adds nums[1] to arr1.
2. The second operation adds nums[2] to arr2.
3. for the ith operation:
3.1. if the number of elements greater than nums[i] in arr1 is greater than the number of elements greater than nums[i] in arr2, add nums[i] to arr1.
3.2. if the number of elements greater than nums[i] in arr1 is less than the number of elements greater than nums[i] in arr2, add nums[i] to arr2.
3.3. If the number of elements greater than nums[i] in arr1 and arr2 are equal, add nums[i] to the array with fewer elements.
3.4. if still equal, add nums[i] to arr1.
Concatenate arr1 and arr2 to form the result array result.
Requires the return of an array of integers, result.
Input: nums = [2,1,3,3].
Output: [2,3,1,3].
Explanation: arr1 = [2] and arr2 = [1] after the first two operations.
In the third operation, the number of elements greater than 3 in both arrays is zero and their lengths are equal, so nums[3] is appended to arr1.
In the fourth operation, the number of elements greater than 3 in both arrays is zero, but arr2 is smaller, so append nums[4] to arr2.
After 4 operations, arr1 = [2,3] and arr2 = [1,3].
Therefore, the result of the concatenated array is [2,3,1,3].
Answer 2024-08-28:
chatgpt
Title from leetcode3072.
The broad steps are as follows:
1. Create a new functiongreaterCount(arr, val)
for calculating arrays ofarr
greater thanval
The number of elements of the
2. Define an empty arrayarr1
cap (a poem)arr2
and create two BinaryIndexedTree data structures.tree1
respond in singingtree2
。
3. For arraysnums
Each element in the
3.1. Sort the current element by index and record the position of each element in the sorted array using the Binary Indexed Tree.
3.2. Perform the first two operations: transfer thenums[0]
become a memberarr1
willnums[1]
become a memberarr2
。
3.3. start traversing from the third element:
3.3.1. Calculationsarr1
cap (a poem)arr2
The number of elements greater than the current element in the array is selected according to the rules, and the corresponding Binary Indexed Tree is updated.
4. Return willarr1
cap (a poem)arr2
A concatenated array of resultsresult
。
The total time complexity is analyzed as O(n log n), where n is the arraynums
The length of the
The total extra space complexity is O(n) and is mainly used to store the sorted array, the index mapping table, the two Binary Indexed Tree structures, and the result array.
The full Go code is below:
package main
import (
"fmt"
"sort"
)
type BinaryIndexedTree struct {
tree []int
}
func NewBinaryIndexedTree(n int) *BinaryIndexedTree {
return &BinaryIndexedTree{tree: make([]int, n+1)}
}
func (bit *BinaryIndexedTree) Add(i int) {
for i < len() {
[i]++
i += i & -i
}
}
func (bit *BinaryIndexedTree) Get(i int) int {
sum := 0
for i > 0 {
sum += [i]
i -= i & -i
}
return sum
}
func resultArray(nums []int) []int {
n := len(nums)
sortedNums := make([]int, n)
copy(sortedNums, nums)
(sortedNums)
index := make(map[int]int)
for i, num := range sortedNums {
index[num] = i + 1
}
arr1, arr2 := []int{nums[0]}, []int{nums[1]}
tree1, tree2 := NewBinaryIndexedTree(n), NewBinaryIndexedTree(n)
(index[nums[0]])
(index[nums[1]])
for i := 2; i < n; i++ {
count1 := len(arr1) - (index[nums[i]])
count2 := len(arr2) - (index[nums[i]])
if count1 > count2 || (count1 == count2 && len(arr1) <= len(arr2)) {
arr1 = append(arr1, nums[i])
(index[nums[i]])
} else {
arr2 = append(arr2, nums[i])
(index[nums[i]])
}
}
return append(arr1, arr2...)
}
func main() {
nums := []int{2, 1, 3, 3}
(resultArray(nums))
}
The complete code for rust is below:
use std::collections::HashMap;
struct BinaryIndexedTree {
tree: Vec<i32>,
}
impl BinaryIndexedTree {
fn new(n: usize) -> Self {
BinaryIndexedTree { tree: vec![0; n+1] }
}
fn add(&mut self, mut i: usize) {
while i < () {
[i] += 1;
i += i & (!i + 1);
}
}
fn get(&self, mut i: usize) -> i32 {
let mut sum = 0;
while i > 0 {
sum += [i];
i -= i & (!i + 1);
}
sum
}
}
fn result_array(nums: &mut Vec<i32>) -> Vec<i32> {
let n = ();
let mut sorted_nums = ();
sorted_nums.sort();
let mut index = HashMap::new();
for (i, &num) in sorted_nums.iter().enumerate() {
(num, i + 1);
}
let mut arr1 = vec![nums[0]];
let mut arr2 = vec![nums[1]];
let mut tree1 = BinaryIndexedTree::new(n);
let mut tree2 = BinaryIndexedTree::new(n);
(*(&nums[0]).unwrap());
(*(&nums[1]).unwrap());
for i in 2..n {
let count1 = () as i32 - (*(&nums[i]).unwrap());
let count2 = () as i32 - (*(&nums[i]).unwrap());
if count1 > count2 || (count1 == count2 && () <= ()) {
(nums[i]);
(*(&nums[i]).unwrap());
} else {
(nums[i]);
(*(&nums[i]).unwrap());
}
}
let mut result = vec![];
(&mut arr1);
(&mut arr2);
result
}
fn main() {
let mut nums = vec![2, 1, 3, 3];
println!("{:?}", result_array(&mut nums));
}