数据结构与算法之RandomPool结构和岛问题
生活随笔
收集整理的這篇文章主要介紹了
数据结构与算法之RandomPool结构和岛问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
數據結構與算法之RandomPool結構和島問題
目錄
1. RandomPool結構
(一)題目概述
(二)思路分析
(三)代碼實現
import java.util.HashMap;public class Code_02_RandomPool {public static class Pool<K> {private HashMap<K, Integer> keyIndexMap;private HashMap<Integer, K> indexKeyMap;private int size;public Pool() {this.keyIndexMap = new HashMap<K, Integer>();this.indexKeyMap = new HashMap<Integer, K>();this.size = 0;}public void insert(K key) {if (!this.keyIndexMap.containsKey(key)) {this.keyIndexMap.put(key, this.size);this.indexKeyMap.put(this.size++, key);}}public void delete(K key) {if (this.keyIndexMap.containsKey(key)) {int deleteIndex = this.keyIndexMap.get(key);int lastIndex = --this.size;K lastKey = this.indexKeyMap.get(lastIndex);this.keyIndexMap.put(lastKey, deleteIndex);this.indexKeyMap.put(deleteIndex, lastKey);this.keyIndexMap.remove(key);this.indexKeyMap.remove(lastIndex);}}public K getRandom() {if (this.size == 0) {return null;}int randomIndex = (int) (Math.random() * this.size); // 0 ~ size -1return this.indexKeyMap.get(randomIndex);}}public static void main(String[] args) {Pool<String> pool = new Pool<String>();pool.insert("nu");pool.insert("li");pool.insert("a");System.out.println(pool.getRandom());System.out.println(pool.getRandom());System.out.println(pool.getRandom());System.out.println(pool.getRandom());System.out.println(pool.getRandom());System.out.println(pool.getRandom());}}2. 島問題
(一)題目概述
(二)思路
(三)代碼實現
public class Code_03_Islands {public static int countIslands(int[][] m) {if (m == null || m[0] == null) {return 0;}int N = m.length;int M = m[0].length;int res = 0;for (int i = 0; i < N; i++) {for (int j = 0; j < M; j++) {if (m[i][j] == 1) {res++;infect(m, i, j, N, M);}}}return res;}public static void infect(int[][] m, int i, int j, int N, int M) {if (i < 0 || i >= N || j < 0 || j >= M || m[i][j] != 1) {return;}m[i][j] = 2;infect(m, i + 1, j, N, M);infect(m, i - 1, j, N, M);infect(m, i, j + 1, N, M);infect(m, i, j - 1, N, M);}public static void main(String[] args) {int[][] m1 = { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0, 1, 1, 1, 0 }, { 0, 1, 1, 1, 0, 0, 0, 1, 0 },{ 0, 1, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 1, 0, 0 }, { 0, 0, 0, 0, 1, 1, 1, 0, 0 },{ 0, 0, 0, 0, 0, 0, 0, 0, 0 }, };System.out.println(countIslands(m1));int[][] m2 = { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 1, 1, 1, 1, 0 }, { 0, 1, 1, 1, 0, 0, 0, 1, 0 },{ 0, 1, 1, 0, 0, 0, 1, 1, 0 }, { 0, 0, 0, 0, 0, 1, 1, 0, 0 }, { 0, 0, 0, 0, 1, 1, 1, 0, 0 },{ 0, 0, 0, 0, 0, 0, 0, 0, 0 }, };System.out.println(countIslands(m2));}}編譯結果:
總結
以上是生活随笔為你收集整理的数据结构与算法之RandomPool结构和岛问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构与算法之完全二叉树的节点个数
- 下一篇: 数据结构与算法之前缀数