29 July 2019
Angular (44) -- Store Recipes via Effects
by Jerry Zhang
LeetCode Day 24: P169. Majority Element (Easy)
题目:
给一个长度为n的数组,找出重复次数最多的那个数,重复次数多于n/2。
我的思路:
首先想到的是HashMap。但是为了性能,尽可能不用。没想到什么好办法,直接看答案了。
Discuss:
class Solution {
public int majorityElement(int[] array) {
int count = 0;
Integer candidate = null;
for (int num : array) {
if (count == 0) { // no majority element in prefix
candidate = num; // selects new candidate majority element
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}
并非最快的。
最优解:
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
把数组排个序,中点位置上的数一定是那个大数。
Angular:
Add a new Action, StoreRecipes
export const STORE_RECIPES = '[Recipe] Store Recipes';
export class StoreRecipes implements Action {
readonly type = STORE_RECIPES;
}
Add a new effect, storeRecipes
@Effect({dispatch: false})
storeRecipes = this.actions$.pipe(
ofType(RecipesActions.STORE_RECIPES),
withLatestFrom(this.store.select('recipes')),
switchMap(([actionData, recipesState]) => {
return this.http
.put(
'https://recipebook-cc2b1.firebaseio.com/recipes.json',
recipesState.recipes
);
})
);
withLatestFrom
merges a value from another observable into this observable.