【Lintcode】1562. Number of Restaurants
題目地址:
https://www.lintcode.com/problem/number-of-restaurants/description
給定一個長 l l l的列表,裡面含的是各個餐館的座標。顧客的座標是 ( 0 , 0 ) (0,0) (0,0),給定一個正整數 n n n,先尋找離顧客最近的 n n n個餐館,設這 n n n個餐館離顧客的最遠距離是 d d d,再按照列表原來的順序找到前 n n n個距離小於等於 d d d的餐館座標,將這些座標返回。如果不足 n n n個則返回空列表。這裡的距離取歐幾里得距離。
先將原列表深拷貝一份,然後對新列表排序,找到第 n n n個餐館與顧客的距離 d d d,然後再遍歷原列表,找到前 n n n個距離也小於等於 d d d的餐館座標即可。程式碼如下:
import java.util.ArrayList;
import java.util.List;
public class Solution {
/**
* @param restaurant:
* @param n:
* @return: nothing
*/
public List<List<Integer>> nearestRestaurant(List<List<Integer>> restaurant, int n) {
// Write your code here
if (restaurant.size() == n) {
return restaurant;
}
if (restaurant.size() < n) {
return new ArrayList<>();
}
List<List<Integer>> res = new ArrayList<>(restaurant);
res.sort((r1, r2) -> Integer.compare(disSqr(r1), disSqr(r2)));
List<Integer> farthest = res.get(n - 1);
int farDisSqr = disSqr(farthest);
List<List<Integer>> list = new ArrayList<>();
for (List<Integer> rest : restaurant) {
if (disSqr(rest) <= farDisSqr) {
list.add(rest);
}
if (list.size() == n) {
break;
}
}
return list;
}
private int disSqr(List<Integer> rest) {
int x = rest.get(0), y = rest.get(1);
return x * x + y * y;
}
}
時間複雜度 O ( l log l ) O(l\log l) O(llogl),空間 O ( l ) O(l) O(l)。
相關文章
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1218. Number Complement
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- JavaScript Number()JavaScript
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1850. Pick ApplesAPP
- 【Lintcode】572. Music PairsAI
- 【Lintcode】318. Character Grid
- 【Lintcode】1891. Travel Plan
- Kata:Hamming number
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.NaNNaN
- JavaScript Number 物件JavaScript物件
- Leetcode Number of islandsLeetCode
- [LintCode/LeetCode] Check Sum of K PrimesLeetCode
- [LintCode]NumberofIslands(島嶼個數)
- lintcode-514-柵欄染色
- 【Lintcode】1322. Product Equal B
- 【Lintcode】191. Maximum Product Subarray