單例singleton(題號204) 問題描述
單例 是最為最常見的設計模式之一。對於任何時刻,如果某個類只存在且最多存在一個具體的執行個體,那麼我們稱這種設計模式為單例。例如,對於 class Mouse (不是動物的mouse哦),我們應將其設計為 singleton 模式。
你的任務是設計一個 getInstance 方法,對於給定的類,每次調用 getInstance 時,都可得到同一個執行個體。
範例(Java中):
A a = A.getInstance();A b = A.getInstance();
a應等於b。 解答過程
若是看過設計模式的應該都清楚,單例是一種建立型模式。並且單例類只能有一個執行個體,必須自己建立自己的唯一執行個體,必須給其他對象提供這一執行個體。一般有如下幾種實現方式:
懶漢式,線程不安全:
public class Singleton{ private static Singleton instance; private Singletion(){} public static Singleton getInstance(){ if(instance==null){ instance = new Singletan(); } } }
懶漢式,安全執行緒:
public class Singleton{ private static Singleton instance; private Singletion(){} public static synchronized Singleton getInstance(){ if(instance==null){ instance = new Singletan(); } } }
餓漢式(最常用):
public class Singleton{ private static Singleton instance = new Singleton(); private Singletion(){} public static Singleton getInstance(){ return instance; } }
雙重鎖(DCL):
public class Singleton{ private volatile static Singleton singleton; private Singletion(){} public static Singleton getInstance(){ if(singleton==null){ synchronized(Singleton.class){ if(singleton == null){ singleton = new Singleton(); } } } return singleton; } } 二叉樹的路徑和(題號376) 問題描述
給定一個二叉樹,找出所有路徑中各節點相加總和等於給定 目標值 的路徑。
一個有效路徑,指的是從根節點到分葉節點的路徑。
1
/ \
2 4
/ \
2 3
返回:
[
[1, 2, 2],
[1, 4]
] 演算法解答
讀取樹的路徑最先想到的應該是樹的遍曆,這裡的遍曆方式是先序遍曆,其次,最簡單的就是使用DFS(深度優先遍曆)。
DFS的遍曆順序為1->2->2->3->4,邏輯自然明了。
下面給出鄰接矩陣模型類AMWGraph.java,其中depthFirstSearch(),broadFirstSearch
()分別代表深度優先和廣度優先遍曆。
import java.util.ArrayList;import java.util.LinkedList;/** * @description 鄰接矩陣模型類 * @author beanlam * @time 2015.4.17 */public class AMWGraph { private ArrayList vertexList;//儲存點的鏈表 private int[][] edges;//鄰接矩陣,用來儲存邊 private int numOfEdges;//邊的數目 public AMWGraph(int n) { //初始化矩陣,一維數組,和邊的數目 edges=new int[n][n]; vertexList=new ArrayList(n); numOfEdges=0; } //得到結點的個數 public int getNumOfVertex() { return vertexList.size(); } //得到邊的數目 public int getNumOfEdges() { return numOfEdges; } //返回結點i的資料 public Object getValueByIndex(int i) { return vertexList.get(i); } //返回v1,v2的權值 public int getWeight(int v1,int v2) { return edges[v1][v2]; } //插入結點 public void insertVertex(Object vertex) { vertexList.add(vertexList.size(),vertex); } //插入結點 public void insertEdge(int v1,int v2,int weight) { edges[v1][v2]=weight; numOfEdges++; } //刪除結點 public void deleteEdge(int v1,int v2) { edges[v1][v2]=0; numOfEdges--; } //得到第一個鄰接結點的下標 public int getFirstNeighbor(int index) { for(int j=0;j<vertexList.size();j++) { if (edges[index][j]>0) { return j; } } return -1; } //根據前一個鄰接結點的下標來取得下一個鄰接結點 public int getNextNeighbor(int v1,int v2) { for (int j=v2+1;j<vertexList.size();j++) { if (edges[v1][j]>0) { return j; } } return -1; } //私人函數,深度優先遍曆 private void depthFirstSearch(boolean[] isVisited,int i) { //首先訪問該結點,在控制台列印出來 System.out.print(getValueByIndex(i)+" "); //置該結點為已訪問 isVisited[i]=true; int w=getFirstNeighbor(i);// while (w!=-1) { if (!isVisited[w]) { depthFirstSearch(isVisited,w); } w=getNextNeighbor(i, w); } } //對外公開函數,深度優先遍曆,與其同名私人函數屬於方法重載 public void depthFirstSearch() { for(int i=0;i<getNumOfVertex();i++) { //因為對於非連通圖來說,並不是通過一個結點就一定可以遍曆所有結點的。 if (!isVisited[i]) { depthFirstSearch(isVisited,i); } } } //私人函數,廣度優先遍曆 private void broadFirstSearch(boolean[] isVisited,int i) { int u,w; LinkedList queue=new LinkedList(); //訪問結點i System.out.print(getValueByIndex(i)+" "); isVisited[i]=true; //結點入隊列 queue.addlast(i); while (!queue.isEmpty()) { u=((Integer)queue.removeFirst()).intValue(); w=getFirstNeighbor(u); while(w!=-1) { if(!isVisited[w]) { //訪問該結點 System.out.print(getValueByIndex(w)+" "); //標記已被訪問 isVisited[w]=true; //入隊列 queue.addLast(w); } //尋找下一個鄰接結點 w=getNextNeighbor(u, w); } } } //對外公開函數,廣度優先遍曆 public void broadFirstSearch() { for(int i=0;i<getNumOfVertex();i++) { if(!isVisited[i]) { broadFirstSearch(isVisited, i); } } }}
這裡給出另一種解法:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /** * @param root the root of binary tree * @param target an integer * @return all valid paths */ public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) { // Write your code here List<List<Integer>> list = new ArrayList<List<Integer>>(); if(root==null) return list; if(root.left==null&&root.right==null){ if(root.val==target){ List<Integer> _list = new ArrayList<Integer>(); _list.add(root.val); list.add(_list); } return list; } list.addAll(binaryTreePathSum(root.left,target-root.val)); list.addAll(binaryTreePathSum(root.right,target-root.val)); for(List<Integer> i :list) i.add(0,root.val); return list; } }字串置換(題號211)
給定兩個字串,請設計一個方法來判定其中一個字串是否為另一個字串的置換。
置換的意思是,通過改變順序可以使得兩個字串相等。
“abc” 為 “cba” 的置換。
“aabc” 不是 “abcc” 的置換。
public class Solution {/* * @param A: a string * @param B: a string * @return: a boolean */ public boolean Permutation(String A, String B) { // write your code here int index =0; if(A.length()==0&&B.length()==0) return true; if(A.length() == B.length()){ String _A[] = A.split(""); String _B[] = B.split(""); Map<String,Integer> mapA = new TreeMap<String,Integer>(); Map<String,Integer> mapB = new TreeMap<String,Integer>(); for(int i = 0;i<_A.length;i++){ Integer num_A = mapA.get(_A[i]); Integer num_B = mapB.get(_B[i]); mapA.put(_A[i],num_A==null?1:num_A+1); mapB.put(_B[i],num_B==null?1:num_B+1); } Iterator<String> iter = mapA.keySet().iterator(); while(iter.hasNext()){ String key = (String)iter.next(); if(!mapA.get(key).equals(mapB.get(key))) break; else index++; } if(index==mapA.keySet().size()) return true; else return false; }else return false; }}迴文數(題號491)
判斷一個正整數是不是迴文數。
迴文數的定義是,將這個數反轉之後,得到的數仍然是同一個數。
11, 121, 1, 12321 這些是迴文數。
23, 32, 1232 這些不是迴文數。
很簡單,思想也很多,這裡貼出其中一種演算法:
public class Solution {/* * @param num: a positive number * @return: true if it's a palindrome or false */ public boolean isPalindrome(int num) { // write your code here LinkedList<String> list = new LinkedList<String>(); String s = Integer.toString(num); String _s[] = s.split(""); list.addAll(Arrays.asList(_s)); while(list.size()>1){ if(list.getFirst().equals(list.getLast())){ list.removeFirst(); list.removeLast(); }else break;; } if(list.size()>1) return false; else return true;}}