Lintcode algorithm Analysis (i.)

Source: Internet
Author: User
Tags addall valid lintcode
Single Case Singleton (question number 204) Problem Description

Singleton is one of the most common design patterns. For any moment, if a class exists only and there is at most one concrete instance, then we call this design pattern a singleton. For example, for class Mouse (not Animal Mouse OH), we should design it as singleton mode.

Your task is to design a getinstance method that, for a given class, can get the same instance each time the getinstance is called.

Sample (in Java):

A = A.getinstance ();
A B = a.getinstance ();

A should be equal to B. Solution Process

If you have seen the design pattern, it should be clear that the singleton is a type of creation pattern. And a singleton class can have only one instance, and must create its own unique instance, which must be provided to other objects. Generally there are several ways to achieve this:

Lazy, thread-insecure:

public class singleton{
    private static Singleton instance;
    Private Singletion () {} public
    static Singleton getinstance () {
        if (instance==null) {
            instance = new Singletan ();}}} 

Lazy, thread-safe:

public class singleton{
    private static Singleton instance;
    Private Singletion () {} public
    static synchronized Singleton getinstance () {
        if (instance==null) {
            instance = new Singletan ();}} 
}   

A Hungry man type (most commonly used):

public class singleton{
    private static Singleton instance = new Singleton ();
    Private Singletion () {} public
    static Singleton getinstance () {
        return instance;
    } 
}   

Double Lock (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;
    } 
}   
two The path of the fork Tree and (question number 376) Problem Description

Given a binary tree, find the path where all the nodes in all the paths sum up equal to the given target value.

A valid path that refers to the path from the root node to the leaf node.
1
/ \
2 4
/ \
2 3
Return:
[
[1, 2, 2],
[1, 4]
] Algorithm Solution

The path to the tree is the first to think of the tree traversal, where the traversal is the first sequence traversal, and secondly, the simplest is to use DFS (depth-first traversal).
The traversal order of Dfs is 1->2->2->3->4, and the logic is naturally clear.
The following gives the adjacency matrix model class Amwgraph.java, where Depthfirstsearch (), Broadfirstsearch
() represent depth-first and breadth-first traversal respectively.

Import java.util.ArrayList;
Import java.util.LinkedList; /** * @description adjacency Matrix Model class * @author Beanlam * @time 2015.4.17 */public class Amwgraph {private ArrayList verte
        xlist;//List of storage points private int[][] edges;//adjacency matrix, used to store the number of edge private int numofedges;//edges public amwgraph (int n) {
        Initialize matrix, one-dimensional array, and number of edges edges=new int[n][n];
        Vertexlist=new ArrayList (n);
    numofedges=0;
    }//Gets the number of nodes public int Getnumofvertex () {return vertexlist.size ();
    }//Get the number of edges public int getnumofedges () {return numofedges;
    }//Returns data for node I, public Object getvaluebyindex (int i) {return vertexlist.get (i);
    }//Returns the weight of the v1,v2 public int getweight (int v1,int v2) {return EDGES[V1][V2];
    }//Insert node public void Insertvertex (Object vertex) {Vertexlist.add (Vertexlist.size (), vertex);
       }//Insert node public void Insertedge (int v1,int v2,int weight) {edges[v1][v2]=weight; numofedges++;
        }//delete node public void Deleteedge (int v1,int v2) {edges[v1][v2]=0;
    numofedges--;
            }//Gets the subscript public int Getfirstneighbor (int index) {for (int j=0;j<vertexlist.size (); j + +) of the first adjacency node {
            if (edges[index][j]>0) {return J;
    }} return-1; }//Based on the subscript of the previous adjacency node, gets the next adjacency node public int getnextneighbor (int v1,int v2) {for (int j=v2+1;j<vertexlist.si
            Ze (); j + +) {if (edges[v1][j]>0) {return J;
    }} return-1; }//Private function, depth first traverse private void Depthfirstsearch (boolean[] isvisited,int i) {//First access the node, print it out in the console Sy
        Stem.out.print (Getvaluebyindex (i) + "");

        The node is visited Isvisited[i]=true; int W=getfirstneighbor (i),//while (W!=-1) {if (!isvisited[w]) {Depthfirstsearch (IsV
            ISITED,W); } W=getnextneighbor (I,W); }}//External public function, depth-first traversal, with its namesake private function belongs to method overload public void Depthfirstsearch () {for (int I=0;i<getnumofvertex ()
            ; i++) {//Because for non-connected graphs, it is not possible to traverse all nodes through a node.
            if (!isvisited[i]) {depthfirstsearch (isvisited,i);
        }}}//Private function, breadth first traverse private void Broadfirstsearch (boolean[] isvisited,int i) {int u,w;

        LinkedList queue=new LinkedList ();
        Access node I System.out.print (Getvaluebyindex (i) + "");
        Isvisited[i]=true;
        Node into the queue queue.addlast (i);
            while (!queue.isempty ()) {u= ((Integer) Queue.removefirst ()). Intvalue ();
            W=getfirstneighbor (U); while (W!=-1) {if (!isvisited[w]) {//accesses the node System.out.print (getval
                    Uebyindex (W) + "");
                    Mark has been accessed by isvisited[w]=true;
        Into the queue queue.addlast (W);        }//Look for the next adjacency node W=getnextneighbor (u, W);  }}}//external public function, breadth-first traversal of publicly void Broadfirstsearch () {for (int i=0;i<getnumofvertex (); i++)
            {if (!isvisited[i]) {Broadfirstsearch (isvisited, i);
 }
        }
    }
}

Here is another solution:

/** * Definition of TreeNode: * public class TreeNode {* public int val;
 * Public TreeNode left and 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 intege R * @return All valid paths */public list<list<integer>> binarytreepathsum (TreeNode root, int t Arget) {//Write your code here list<list<integer>> List = new ARRAYLIST&LT;LIST&LT;INTEGER&G
        T;> ();
        if (root==null) return list; if (root.left==null&&root.right==null) {if (root.val==target) {list<integer> _lis
                 t = 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;
 }
 }
string Substitution (problem number 211)

Given two strings, design a method to determine whether one of the strings is a permutation of another string.

Permutation means that two strings can be equal by changing the order.
"ABC" is the replacement of "CBA".

"AABC" is not a permutation of "ABCC".

public class Solution {/* * @param a:a String * @param b:a String * @return: A Boolean */public boolean Permut
        ation (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;
 }
}
palindrome Number (question number 491)

Determines whether a positive integer is a palindrome number.

The palindrome definition is that after the number is reversed, the resulting number is still the same number.
11, 121, 1, 12321 these are palindrome numbers.

23, 32, 1232 These are not palindrome numbers.

It's simple, there's a lot of thought, and here's one of the algorithms:

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 Linkedlis T<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;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.