Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
Note:
(1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
(2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
Design a data structure to find the frequency of a given value in a given subarray.
The frequency of a value in a subarray is the number of occurrences of that value in the subarray.
Implement the RangeFreqQuery class:
RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr.
int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right].
A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).
Explanation
RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);
rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]
rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.
</pre>
Constraints:
1 <= arr.length <= 10<sup>5</sup>
1 <= arr[i], value <= 10<sup>4</sup>
0 <= left <= right < arr.length
At most 10<sup>5</sup> calls will be made to query
from heapq import heapreplace, heappush from collections import Counter
deftopKFrequent(self, nums: List[int], k: int) -> List[int]: dict = Counter(nums) freq_dict = [(v, k) for k, v indict.items()] res = [] for i inrange(len(freq_dict)): heappush(res, freq_dict[i]) iflen(res) > k: heappop(res) return [k for v, k in res]
public List<Integer> topKFrequent(int[] nums, int k) { List<Integer> result = newArrayList<Integer>(); HashMap<Integer, Integer> map = newHashMap<Integer, Integer>(); for(int i=0;i<nums.length;i++){ if(map.containsKey(nums[i])) map.put(nums[i], map.get(nums[i])+1); else map.put(nums[i], 1); } Node[] f = newNode[map.size()]; Iteratorit= map.entrySet().iterator(); int j=0; while(it.hasNext()){ Map.Entrypair= (Map.Entry)it.next(); Nodenode=newNode((int)pair.getKey(), (int)pair.getValue()); f[j++] = node; } hselect(f, k); for(int i=0;i<k;i++) result.add(f[i].key); return result; } publicvoidhselect(Node a[], int k){ // min heap with size=k for (inti= k / 2; i >= 0; i--) { minHeapify(a, i, k); } for (inti= k; i < a.length; i++) { if (a[i].value > a[0].value) { swap(a, i, 0); minHeapify(a, 0, k); } } }
publicvoidminHeapify(Node[] arr, int i, int n) { intsmallest= i; intl= left(i); intr= l + 1; if (l < n && arr[l].key < arr[smallest].key) smallest = l; if (r < n && arr[r].key < arr[smallest].key) smallest = r; if (smallest != i) { swap(arr, i, smallest); minHeapify(arr, smallest, n); } }
privateintleft(int i) { return2 * i + 1; }
privatevoidswap(Node[] arr, int index1, int index2) { Nodetmp= arr[index1]; arr[index1] = arr[index2]; arr[index2] = tmp; }
classNode { int key; int value; publicNode(int k, int v){ key = k; value = v; } public String toString(){ return"("+key+","+value+")"; } }
桶排序要用List串联起元素,例如[1,2],k=2,频数为1的元素有两个,所以桶的内容应该是List。Python用[[] for _ in range(len(nums) + 1)]
桶数量为原数组大小+1,例如一个元素[1], 它的频数为1,而频数为0是不会出现。
逆序遍历所有桶,只要结果集个数为k,就停止循环。
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from collections import Counter
deftopKFrequent(self, nums: List[int], k: int) -> List[int]: di = Counter(nums) freq = [[] for _ inrange(len(nums) + 1)] for key, val in di.items(): freq[val].append(key) res = [] for i inrange(len(freq) - 1, 0, -1): for n in freq[i]: if k > 0: res.append(n) k -= 1 return res
题目可以包装成:给定一个文档,返回其前k个出现次数最多的单词。
Given a document, return the k most frequent words. Assume punctuation are removed.
Given a non-empty array of strings, return the k most frequent elements.
deftwoSum(self, nums: List[int], target: int) -> List[int]: for i inrange(len(nums)): for j inrange(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j]
1 2 3 4 5 6 7 8 9 10
deftwoSum(self, nums: List[int], target: int) -> List[int]: temp.sort() i, j = 0, len(temp) - 1 while i < j: if temp[i][0] + temp[j][0] < target: i += 1 elif temp[i][0] + temp[j][0] > target: j -= 1 else: return [temp[i][1], temp[j][1]]
1 2 3 4 5 6
deftwoSum(self, nums: List[int], target: int) -> List[int]: nums_dict = {} for i, n inenumerate(nums): if target - n in nums_dict: return [nums_dict[target - n], i] nums_dict[n] = i
You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the i<sup>th</sup> plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.
Each plant needs a specific amount of water. You will water the plants in the following way:
Water the plants in order from left to right.
After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.
You cannot refill the watering can early.
You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis.
Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the i<sup>th</sup> plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants.
Example 1:
<pre>Input: plants = [2,2,3,3], capacity = 5
Output: 14
Explanation: Start at the river with a full watering can:
Walk to plant 0 (1 step) and water it. Watering can has 3 units of water.
Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water.
Since you cannot completely water plant 2, walk back to the river to refill (2 steps).
Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water.
Since you cannot completely water plant 3, walk back to the river to refill (3 steps).
Walk to plant 3 (4 steps) and water it.
Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.
</pre>
Example 2:
<pre>Input: plants = [1,1,1,4,2,3], capacity = 4
Output: 30
Explanation: Start at the river with a full watering can:
Water plants 0, 1, and 2 (3 steps). Return to river (3 steps).
Water plant 3 (4 steps). Return to river (4 steps).
Water plant 4 (5 steps). Return to river (5 steps).
defwateringPlants(self, plants: List[int], capacity: int) -> int: sum, steps = 0, 0 for i, n inenumerate(plants): sum += plants[i] ifsum <= capacity: continue steps += i * 2# back to river sum = plants[i] ifsum > 0: steps += len(plants) return steps