1337.矩阵战斗力最弱的K行
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
int row = mat[0].size();
int col = mat.size();
unordered_map<int, int> hash;
for (int i = 0; i < col; i++) {
int sum = 0;
for (int j = 0; j < row; j++) {
if (mat[i][j] == 1)
sum++;
else
break;
}
hash[i] = sum;
}
vector<pair<int,int>> help;
for (auto it = hash.begin();it!=hash.end();it++)
help.push_back(make_pair(it->first,it->second));
sort(help.begin(), help.end(), helpSort);
vector<int> ans;
int i = 0;
for (auto [key, v] : help){
if(i == k)
break;
ans.push_back(key);
i++;
}
return ans;
}
static bool helpSort(pair<int, int> a, pair<int, int> b){
if(a.second == b.second)
return a.first < b.first;
return a.second < b.second;
}
这到题的主要思想是把每行的行号和这一行对应的战斗力都从存储在一个哈希表里,在将键值对根据值的大小,从小到大排序,排完序在将前k行提取出来,返回整k对键值对就好了,但是排序的时候的规则是,如果第i行和第k行的战斗力相等,就看i和j谁大,谁打谁的战斗力强,这个时候就很需要c++的排序函数大显神威了
852.山脉数组的峰顶索引
/**
* @param {number[]} arr
* @return {number}
*/
var peakIndexInMountainArray = function(arr) {
var l=1,r=arr.length-1;
let ans;
while (l <= r){
var mid = Math.floor(l+(r-l)/2);
if (arr[mid] > arr[mid+1]){
ans = mid;
r = mid-1;
}
else
l = mid+1;
}
return ans;
};
1385.两个数组间的距离值
JavaScript
/**
* @param {number[]} arr1
* @param {number[]} arr2
* @param {number} d
* @return {number}
*/
var findTheDistanceValue = function(arr1, arr2, d) {
var ans = 0;
for (var i of arr1){
var all = true;
for (var j of arr2){
if (Math.abs(i-j) <=d)
all = false;
}
if (all)
ans ++;
}
return ans;
};
C++
class Solution {
public:
int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {
int num = 0;
for (int i = 0; i < arr1.size() ; i++ ){
bool no = true;
for (int j=0;j<arr2.size();j++){
if(abs(arr1[i] - arr2[j]) <= d)
no = false;
}
if(no)
num ++;
}
return num;
}
};
Java
int num = 0;
for (int i = 0; i < arr1.length ; i++ ){
boolean no = true;
for (int j=0;j<arr2.length;j++){
if(Math.abs(arr1[i] - arr2[j]) <= d)
no = false;
}
if(no == true)
num ++;
}
return num;
}
C
int findTheDistanceValue(int* arr1, int arr1Size, int* arr2, int arr2Size, int d){
int num = 0,i,j;
for (i = 0; i < arr1Size ; i++ ){
bool no = true;
for (j=0;j<arr2Size;j++){
if(abs(arr1[i] - arr2[j]) <= d)
no = false;
}
if(no == true)
num ++;
}
return num;
}
Python
def findTheDistanceValue(self, arr1, arr2, d):
num = 0
for i in range(len(arr1)):
no = True
for j in range(len(arr2)):
if abs(arr1[i] - arr2[j]) <= d:
no = False
if no == True:
num += 1
return num
Python3
class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
num:int = 0
for i in range(len(arr1)):
no:bool = True
for j in range(len(arr2)):
if abs(arr1[i] - arr2[j]) <= d:
no = False
if no == True:
num += 1
return num