Algorithm
February LeetCoding Challenge 2021
The K Weakest Rows in a Matrix
You are given an m x n binary matrix mat of 1‘s (representing soldiers) and 0‘s (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1‘s will appear to the left of all the 0‘s in each row.
A row i is weaker than a row j if one of the following is true:
- The number of soldiers in row
iis less than the number of soldiers in rowj. - Both rows have the same number of soldiers and
i < j.
Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.
Example 1:
Input: mat =
[[1,1,0,0,0],
[1,1,1,1,0],
[1,0,0,0,0],
[1,1,0,0,0],
[1,1,1,1,1]],
k = 3
Output: [2,0,3]
Explanation:
The number of soldiers in each row is:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
The rows ordered from weakest to strongest are [2,0,3,1,4].
Example 2:
Input: mat =
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]],
k = 2
Output: [0,2]
Explanation:
The number of soldiers in each row is:
- Row 0: 1
- Row 1: 4
- Row 2: 1
- Row 3: 1
The rows ordered from weakest to strongest are [0,2,3,1].
Constraints:
m == mat.lengthn == mat[i].length2 <= n, m <= 1001 <= k <= mmatrix[i][j]is either 0 or 1./*** @param {number[][]} mat* @param {number} k* @return {number[]}*/var kWeakestRows = function(mat, k) {let arr=[];for(let j=0;j<mat.length;j++){let soldierNum=0;for(let i=0;i<mat[0].length;i++){if (mat[j][i]===1){soldierNum++};}arr.push(soldierNum); //每行第一个值组个数列mat[j][0]=soldierNum; //矩阵每行之和累加,保存到每行第一个值};arr.sort((a, b) => a - b);//数列由小到大重新排序arr=arr.slice(0,k); //取前k个值let finalArray=[];arr.forEach((element)=>{ //遍历newArr每个元素for(let j=0;j<mat.length;j++){ //遍历矩阵每行第一个元素查找if(element===mat[j][0]){if(!finalArray.includes(j)){ //如果相等且没重复finalArray.push(j); //返回行数,停止循环查找break;} //如果相等且重复,这个值不要,继续循环找}}});return finalArray;};



Hhhh, every time my algorithm solution runs extremely fast, but occupies super large memory space.Review
Split Payment, a start-up’s brief intro
How to tailor a Resume
Tip
//SquareNums()
const numbers = [2, 7, 9, 171, 52, 33, 14]const toSquare = num => num * num// Write your code here:const squareNums=arr=>arr.map(toSquare);console.log(squareNums(numbers)); //[ 4, 49, 81, 29241, 2704, 1089, 196 ]
//OrderByDescending()
```javascript const sortYears = arr => arr.sort((x, y) => y - x); const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922] console.log(sortYears(years)) // Should print [ 2018, 2011, 1999, 1982, 1970, 1963, 1951, 1922]
//tedious solution, not recommend const sortYears=(years)=>{ let descendYears=[]; years.sort(); for(i=years.length-1;i>=0;i—){ descendYears.push(years[i]) } return descendYears; }
<a name="ZbJsj"></a>## //filter same elements from two arrays```javascriptconst filter = (arr1, arr2) => arr1.filter(item => arr2.includes(item));
//Check elements in objects
const isTheDinnerVegan = arr => arr.every(food => food.source === 'plant');
const dinner = [{name: 'hamburger', source: 'meat'}, {name: 'cheese', source: 'dairy'}, {name: 'ketchup', source:'plant'}, {name: 'bun', source: 'plant'}, {name: 'dessert twinkies', source:'unknown'}];
console.log(isTheDinnerVegan(dinner)) // Should print false
//Sorting items properties in objects
const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32}];
const sortSpeciesByTeeth = arr => arr.sort((a,b)=>a.numTeeth>b.numTeeth);
console.log(sortSpeciesByTeeth(speciesArray))
//Implementing some functionality from the widely-popular lodash.js library
const _={
clamp(number,lower,upper){
const lowerClampedValue=Math.max(number,lower);
const clampedValue=Math.min(lowerClampedValue,upper);
return clampedValue;
},
inRange(number,start,end){
if(end===undefined){
end=start;
start=0;
}
if(start>end){
var temp=end;
end=start;
start=temp;
}
var isInRange=start<=number && number< end;
return isInRange;
},
words(string){
const words=string.split(' ');
return words;
},
pad(string,length){
if(length<=string.length){
return string;
};
const startPaddingLength=Math.floor((length-string.length)/2);
const endPaddingLength=length-string.length-startPaddingLength;
const paddedString=' '.repeat(startPaddingLength)+string+' '.repeat(endPaddingLength);
return paddedString;
},
has(object,key){
const hasValue=object[key];
if(hasValue!=undefined){
return true;
}return false;
},
invert(object){
let invertedObject= {};
for(let key in object){
const originalValue=object[key];
invertedObject[originalValue] = key;
}
return invertedObject;
},
findKey(object, predicate) {
for (let key in object) {
let value = object[key];
let predicateReturnValue = predicate(value);
if (predicateReturnValue) {
return key;
}
}
return undefined;
},
drop(array,n){
if(n===undefined){
n=1;
}
let droppedArray=array.slice(n,array.length);
return droppedArray;
},
dropWhile(array,predicate){
const cb=(element, index)=>{
return !predicate(element, index, array);
};
let dropNumber=array.findIndex(cb);
let droppedArray=this.drop(array,dropNumber);
return droppedArray
},
chunk(array,size=1){
let arrayChunks=[];
for(let i=0;i<array.length;i+=size){
let arrayChunk=array.slice(i,i+size);
arrayChunks.push(arrayChunk);
}
return arrayChunks
}
};
// Do not write or modify code below this line.
module.exports = _;
//Credit card No. Validator
// All valid credit card numbers
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const valid2 = [5, 5, 3, 5, 7, 6, 6, 7, 6, 8, 7, 5, 1, 4, 3, 9];
const valid3 = [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6];
const valid4 = [6, 0, 1, 1, 1, 4, 4, 3, 4, 0, 6, 8, 2, 9, 0, 5];
const valid5 = [4, 5, 3, 9, 4, 0, 4, 9, 6, 7, 8, 6, 9, 6, 6, 6];
// All invalid credit card numbers
const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];
const invalid2 = [5, 7, 9, 5, 5, 9, 3, 3, 9, 2, 1, 3, 4, 6, 4, 3];
const invalid3 = [3, 7, 5, 7, 9, 6, 0, 8, 4, 4, 5, 9, 9, 1, 4];
const invalid4 = [6, 0, 1, 1, 1, 2, 7, 9, 6, 1, 7, 7, 7, 9, 3, 5];
const invalid5 = [5, 3, 8, 2, 0, 1, 9, 7, 7, 2, 8, 8, 3, 8, 5, 4];
// Can be either valid or invalid
const mystery1 = [3, 4, 4, 8, 0, 1, 9, 6, 8, 3, 0, 5, 4, 1, 4];
const mystery2 = [5, 4, 6, 6, 1, 0, 0, 8, 6, 1, 6, 2, 0, 2, 3, 9];
const mystery3 = [6, 0, 1, 1, 3, 7, 7, 0, 2, 0, 9, 6, 2, 6, 5, 6, 2, 0, 3];
const mystery4 = [4, 9, 2, 9, 8, 7, 7, 1, 6, 9, 2, 1, 7, 0, 9, 3];
const mystery5 = [4, 9, 1, 3, 5, 4, 0, 4, 6, 3, 0, 7, 2, 5, 2, 3];
// An array of all the arrays above
const batch = [valid1, valid2, valid3, valid4, valid5, invalid1, invalid2, invalid3, invalid4, invalid5, mystery1, mystery2, mystery3, mystery4, mystery5];
// Add your functions below:
const validateCred=(arr)=>{
let sum=0;
let newArray=arr.slice(0);
for(let i=newArray.length-2;i>=0;i-=2){
newArray[i]*=2;
if(newArray[i]>9){newArray[i]-=9}
}
for(let i=0;i<newArray.length;i++){
sum+=newArray[i]
}
if(sum%10===0){
return true;
}else{
return false;
}
}
console.log(validateCred(invalid4));
const findInvalidCards=(bat)=>{
let invalidCard = [];
let validCard = [];
bat.forEach(function(element){
if(validateCred(element)===false){
invalidCard.push(element);
}else{
validCard.push(element);
}
})
return invalidCard;
};
console.log(findInvalidCards(batch));
const idInvalidCardCompanies=(bat)=>{
let companyNum=[3,4,5,6];
let InvaildCompany=[];
let database = {
'3': 'Amex(American Express)',
'4': 'Visa',
'5': 'Mastercard',
'6': 'Discover'
};
bat.forEach(function(arr){
let firstDigit=arr[0];
if (!companyNum.includes(firstDigit)){
console.log('Company not found');
}else{InvaildCompany.push(database[firstDigit])
}
});
InvaildCompany = InvaildCompany.filter(function(item, index, inputArray) {
return inputArray.indexOf(item) == index;
});
console.log(InvaildCompany);
};
idInvalidCardCompanies(batch);
//Comparing Mysterious Organism’s DNA project, trying to understand
// Returns a random DNA base
const returnRandBase = () => {
const dnaBases = ['A', 'T', 'C', 'G']
return dnaBases[Math.floor(Math.random() * 4)]
}
console.log(returnRandBase(15));
// Returns a random single stand of DNA containing 15 bases
const mockUpStrand = () => {
const newStrand = []
for (let i = 0; i < 15; i++) {
newStrand.push(returnRandBase())
}
return newStrand
}
console.log(mockUpStrand());
// use Factory Function to create a multiple object
const pAequorFactory = (specimenNum, dna = mockUpStrand()) => {
return {
specimenNum,
dna,
mutate() {
return this.dna = returnRandBase();
},
// Method that compare two dna
compareDNA(pAequor) {
console.log(`${this.specimenNum}: ${this.dna}`);
console.log(`${pAequor.specimenNum}: ${pAequor.dna}`);
// Create variables to calculate the percentage of DNA have in common
// and another to save the percentage
let dnaCommon = 0;
let dnaPercentage = 0;
// Loops through two 'dna' array to compare their dna
for(let i = 0; i < this.dna.length; i++) {
if(this.dna[i] === pAequor.dna[i]) {
dnaCommon++;
}
dnaPercentage = (100 / 15) * dnaCommon;
}
console.log(`Specimen #${specimenNum} and specimen #${pAequor.specimenNum} have ${Math.floor(dnaPercentage)}% DNA in common`);
},
// Method that decided it the DNA allow to P.aequor to survive
willLikelySurvive() {
let findGandC = 0;
let survivePercentage = 0;
for(let i = 0; i < this.dna.length; i++) {
if(this.dna[i] === 'G' || this.dna[i] === 'C') {
findGandC++;
}
}
survivePercentage = Math.floor((100 / 15) * findGandC);
if(survivePercentage >= 60) {
return true;
} else {
return false;
}
}
};
};
// Print a simulation
// Compares two organisms 'one' and 'two'
const orgOne = pAequorFactory('9');
const orgTwo = pAequorFactory('6');
orgOne.compareDNA(orgTwo);
// Create 30 pAequor objects that have a DNA allow them to survive
// Save them inside an array
// Declare the empty array
const instancespAequor = [];
let index = 0;
while(index < 30) {
pAequorFactory(index);
if(pAequorFactory(index).willLikelySurvive() === true) {
instancespAequor.unshift(pAequorFactory(index).dna);
index++;
}
}
console.log(instancespAequor);
Share
Popular Language in Blockchain
- Solidity
- JavaScript
- Python
- Go
- Rust
-
Technology Stack
Web
frontend/backend/databases
- devops/security/python
- ruby/javascript/html/css/react
_
- security for _smart contract vulnerabilities
- React is a js framework used to simplify code of highly dynamic website
- http request, exchange data on the Internet
- nodejs, js running on a server
- npm
Libraries and Frameworks
- NMP/Node.js
- _Truffle, _testing tool
- Metamask
- Ganache
- Web3.js
- Ethers.js
- React.js
- Express.js
-
Build a One Year Goal
Learn Smart Contracts Development Solidity 0.6__
- _Build P_rojects
- DeApp with Solidity, Truffle & Web3. Include tests & frontend
- Decentralized Exchange for ERC20 tokens, including tests & frontend with charts
- Find Job
- Solidity Snippets
- find Top Blockchain companies













