public static boolean checkDuplicateWithinK(int[][] mat, int k){ class Cell{ int row; int col; public Cell(int r, int c){ this.row = r; this.col = c; } } int n = mat.length; int m = mat[0].length; k = Math.min(k, n*m); //map from distance to cell postions of the matrix Map> map = new HashMap >(); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(map.containsKey(mat[i][j])){ for(Cell c : map.get(mat[i][j])){ int Dist = Math.abs(i - c.row)+Math.abs(j - c.col); if(Dist <= k){ return true; } if(i - c.row > k){ map.remove(c); } } map.get(mat[i][j]).add(new Cell(i, j)); } else{ map.put(mat[i][j], new HashSet ()); map.get(mat[i][j]).add(new Cell(i, j)); } } } return false; } |
public boolean checkDuplicatesWithinK(int[][] matrix, int k) { //convert matrix to an array int[] arr = Arrays.stream(matrix) .flatMapToInt(Arrays::stream) .toArray(); // Creates an empty hashset HashSetset = new HashSet<>(); // Traverse the input array for (int i = 0; i < arr.length; i++) { // If already present n hash, then we found // a duplicate within k distance if (set.contains(arr[i])) return true; // Add this item to hashset set.add(arr[i]); // Remove the k+1 distant item if (i >= k) set.remove(arr[i - k]); } return false; }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/64971.html
I complete reading JavaScript Enlightenment recently. The book is more about basics in JavaScript and suitable for beginners. Here are a list of my benefits and extensions from the book. Math JavaScri...
摘要:我的博客大家都知道解決了回調(diào)地獄的問(wèn)題。這就是異步的嵌套帶來(lái)的可讀性的問(wèn)題,它是由異步的運(yùn)行機(jī)制引起的。在與第三方團(tuán)隊(duì)溝通之后問(wèn)題得到了解決。這不但使代碼變得臃腫不堪,還進(jìn)一步加劇了可讀性的問(wèn)題。的特征保證了可以解決信任問(wèn)題。 我的github博客 https://github.com/zhuanyongxigua/blog 大家都知道Promise解決了回調(diào)地獄的問(wèn)題。說(shuō)到回調(diào)地獄,...
摘要:為了控制壓測(cè)時(shí)的,則需要實(shí)現(xiàn)邏輯。則是獲取屬性并初始化客戶端客戶端配置則提供了設(shè)置泛化調(diào)用入?yún)⒌囊约敖酉聛?lái)要介紹的部分的全鏈路壓測(cè)中,我們都使用校驗(yàn)請(qǐng)求結(jié)果,壓測(cè)插件中,我們也實(shí)現(xiàn)了基于的校驗(yàn)。 Dubbo 壓測(cè)插件已開源,本文涉及代碼詳見gatling-dubbo Gatling 是一個(gè)開源的基于 Scala、Akka、Netty 實(shí)現(xiàn)的高性能壓測(cè)框架,較之其他基于線程實(shí)現(xiàn)的壓測(cè)框架...
摘要:為了控制壓測(cè)時(shí)的,則需要實(shí)現(xiàn)邏輯。則是獲取屬性并初始化客戶端客戶端配置則提供了設(shè)置泛化調(diào)用入?yún)⒌囊约敖酉聛?lái)要介紹的部分的全鏈路壓測(cè)中,我們都使用校驗(yàn)請(qǐng)求結(jié)果,壓測(cè)插件中,我們也實(shí)現(xiàn)了基于的校驗(yàn)。 Dubbo 壓測(cè)插件已開源,本文涉及代碼詳見gatling-dubbo Gatling 是一個(gè)開源的基于 Scala、Akka、Netty 實(shí)現(xiàn)的高性能壓測(cè)框架,較之其他基于線程實(shí)現(xiàn)的壓測(cè)框架...
閱讀 3125·2021-11-16 11:45
閱讀 5561·2021-09-22 10:57
閱讀 2044·2021-09-08 09:36
閱讀 1873·2021-09-02 15:40
閱讀 2647·2021-07-26 23:38
閱讀 1387·2019-08-30 15:55
閱讀 1068·2019-08-30 15:54
閱讀 1357·2019-08-29 14:06