Java Interview 13| algorithm

Source: Internet
Author: User

Common functions for Java write algorithms:

Stack

void push (E E): pushes the given element into the stack. The deposited element will be at the top of the stack. That is: The first element of a stack
E pop (): Deletes and returns the first element of the stack.

Queue

Boolean offer (E): Appends the element to the end of the queue and returns true if the addition succeeds.
E poll (): Removes and returns the element from the first team.
E Peek (): Returns the first element of the team, but does not delete

Deque is a double-ended queue, with all the methods of stack and queue.

Team first Operation:

Push, Peek, pop

Tail Operation:

Add, offer, Peeklast, Poplast

String manipulation:

Convert ToCharArray () to a char array

CharAt (index) takes a character indexed as index in a string

1. Bubble sort
for (int i=0;i<n;i++) {for   (int j=0;j<n-1-i;j++) {        if (temp[j]>temp[j+1]) {           int t=temp[j];           TEMP[J]=TEMP[J+1];           temp[j+1]=t;}}}   

2. Quick Sort
public void Quicksort (int[] Array,int left,int right) {if (left<right) {int key = Array[left];int Low = left;int High = ri Ght;while (Low

  

3. Find the first index where the substring appears

The implementation of the IndexOf () method, similar to Java, is as follows:

static int indexOf (char[] source, char[] target) {char first = Target[0];int max = (source.length-target.length); t i = 0; I <= Max; i++) {/* look for first character. */if (Source[i]! = first) {while (++i <= max && source[i]! = first);} /* Found first character, now look at the rest of v2 */if (i <= max) {Int J = i + 1;int end = j + target.length-1; fo R (int k = 1; J < end && Source[j] = = Target[k]; j + +, k++); if (j = = end) {/* Found whole string. */return i;}} }return-1;}

4, layered print binary tree and output line-wrapping in the first layer
public void Printfromtoptobottom (TreeNode root) {TreeNode CurrentNode = root;int first = 1;int second = 0;while (currentno De! = null) {if (currentnode.left! = null) {Queue.add (currentnode.left); second++;} if (currentnode.right! = null) {Queue.add (currentnode.right); second++;} first--; System.out.print (Currentnode.val + ""), if (first = = 0) {System.out.println (""); first = Second;second = 0;} CurrentNode = Queue.poll ();}}

  

 

5. Consistent Hash

The consistency hash algorithm can solve the problem of fault tolerance and extensibility.

More virtual nodes are added in the system, which can better solve the load balancing problem.

public class Shard<s> {//S class encapsulates the machine node information, such as name, password, IP, port, etc. private Treemap<long, s> circle;           The whole hash value space is composed of a virtual ring private list<s> shards; Real machine node private final int node_num = 100;  The number of virtual nodes associated with each machine node private final hashfunction hashfunction;          Select a hash () function with low collision rate public Shard (list<s> shards,hashfunction hashfunction) {super ();          This.shards = shards;        This.hashfunction = hashfunction;      Init ();          } private void Init () {//Initialize consistency hash ring circle = new Treemap<long, s> ();              for (int i = 0; I<shards.size (); ++i) {//each real machine node requires an associated virtual node final S shardinfo = Shards.get (i);        Add (Shardinfo); }} ' public void ' Add (S node) {for (int i = 0; i < Node_num; i++) {//virtual nodes are replaced with some specific hash values, thus creating a mapping of the hash value to the real node Circle.put (Hashfunction.hash (node.tostring () + i), node);}} public void Remove (S node) {for (int i = 0; i < node_num; i++) {//Remove all virtual nodes corresponding to the real node (certain hash values) Circle.remove (Hashfunction.hash (node.tostring () + i));}} Public S Getshardinfo (String key) {//Sortedmap<long, s> tail = circle.tailmap (hash (key)),//A virtual section is found clockwise along the ring  Point//if (tail.size () = = 0) {//Return Circle.get (Circle.firstkey ()); }//Return Tail.get (Tail.firstkey ()); Returns the information for the Real machine node corresponding to the virtual node if (Circle.isempty ()) {return null;} Long hash = Hashfunction.hash (key);//If the current hash value is not anchored to the virtual node if (!circle.containskey (hash)) {Sortedmap<long, s> Tailmap = Circle.tailmap (hash); hash = Tailmap.isempty ()? Circle.firstkey (): Tailmap.firstkey ();}    return Circle.get (hash);   }  }

Class Machine {String IP; String Name;public Machine (string IP, string name) {This.ip = Ip;this.name = name;} Public String GetIP () {return IP;} public void setIp (String IP) {this.ip = IP;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}} public class Test {public static void main (string[] args) {Machine A = new Machine ("192.168.0.1", "a"); Machine B = New Machine ("192.168.0.2", "B"); Machine C = new Machine ("192.168.0.3", "C"); list<machine> list = Arrays.aslist (A, B, c); map<string, integer> map = new hashmap<string, integer> (); shard<machine> MCS = new shard<machine> (list, new hashfunction ());//Store 0 to 2000 numbers to see if the number stored on each machine is roughly uniform for ( int i = 0; I < 2000; i++) {String key = i + "";  Machine M = mcs.getshardinfo (key), if (Map.get (M.getip ()) = = null) {Map.put (M.getip (), 0);} else {map.put (M.getip (), (int) Map.get (M.getip ()) + 1);}} iterator<entry<string, integer>> Iterator = Map.entryset (). Iterator (); while (Iterator. Hasnext ()) {entry<string, integer> Entry = Iterator.next (); System.out.println (Entry.getkey () + "/" + Entry.getvalue ());}}}

  

After a run, the results are as follows:

192.168.0.2/599192.168.0.1/698192.168.0.3/700

6. LRU Least Recently used algorithm

To be efficient use hash search, to achieve the least recent words with a doubly linked list

public class LRUCache {private int cacheSize; Private Hashmap<object, entry> nodes;      Cache container, in order to improve the query speed requires this structure private int currentsize; Private Entry first;  The list head private Entry last;        Chain footer Static class Entry {Entry prev;         Entry Next;             Object key;     Object value;          } public LRUCache (int i) {currentsize = 0;          CacheSize = i;    nodes = new Hashmap<object, entry> (i);           }/** * Gets the object in the cache and puts it on the front */public Entry get (object key) {Entry node = nodes.get (key);              if (node! = null) {Movetohead (node);          return node;          } else {return null;          }}/** * Add entry to Hashtable and put entry */public void put (object key, object value) {                    First see if the Hashtable exists for the Entry, and if so, only its value Entry node = nodes.get (key) is updated;      if (node = = null) {        Whether the cache container has exceeded its size.                  if (currentsize >= cacheSize) {nodes.remove (Last.key);              Removelast ();              } else {currentsize++;          } node = new Entry ();          } node.value = value;          Put the most recently used node in the list header, indicating the most recently used.          Movetohead (node);      Nodes.put (key, node); /** * Delete Entry, note: The delete operation will be executed only if the cache is full */public void Remove (Object key) {Entry node = n          Odes.get (key);              Delete if (node! = null) {if (Node.prev! = null) in the linked list {node.prev.next = Node.next;              } if (Node.next! = null) {Node.next.prev = Node.prev;              } if (last = = node) last = Node.prev;          if (first = = node) first = Node.next;      }//delete Nodes.remove (key) in Hashtable; }/** * Delete chainThe tail node of the table, even with the last used entry */private void Removelast () {//the tail of the chain is not empty, then the linked footer is pointed to null. Delete the footer (delete least used cache object) I              F (last! = null) {if (Last.prev! = null) {last.prev.next = null;              } else{first = null;          } last = Last.prev; }}/** * Moves to the list header, indicating that the node is the most recently used */private void Movetohead (Entry node) {if (node =          = first) return;          if (Node.prev! = null) Node.prev.next = Node.next;          if (node.next! = null) Node.next.prev = Node.prev;          if (last = = node) last = Node.prev;              if (first! = null) {Node.next = first;          First.prev = node;          } first = node;          Node.prev = null;          if (last = = null) {last = first;       }/* * Empty cache */public void Clear () {first = null;   last = null;      currentsize = 0;   }    }

7. Producers and consumers

public class Consumerproducerbywaitnotify {public integer monitor = new Integer (1);    public static void Main (string[] args) {consumerproducerbywaitnotify instance = new Consumerproducerbywaitnotify ();    Instance.bootstrap (); } public void Bootstrap () {Godown godown = new Godown (30);//must operate an instance of the same library, otherwise there is no multithreading problem Co            Nsumer C1 = new Consumer (Godown);            Consumer C2 = new Consumer (Godown);                    Consumer C3 = New Consumer (Godown);            Producer P1 = new Producer (ten, Godown);            Producer P2 = new Producer (ten, Godown);            Producer p3 = new Producer (ten, Godown);            Producer P4 = new Producer (ten, Godown);            Producer P5 = new Producer (ten, Godown);            Producer P6 = new Producer (ten, Godown);                Producer P7 = new Producer (ten, Godown);            C1.start ();            C2.start ();            C3.start ();            P1.start ();            P2.start (); P3.sTart ();            P4.start ();            P5.start ();            P6.start ();      P7.start (); }//Warehouse class Godown {public static final int max_size = 100;//MAX inventory public int Curnu M          Current inventory amount Godown (int curnum) {this.curnum = Curnum; }//production of a specified number of products public void produce (int neednum) {synchronized (monitor) {//test need to produce while (Neednum + curnum > Max _size) {System.out.println ("number of products to be produced" + Neednum + "Excess inventory remaining" + (Max_size-curnum) + ", no production tasks can be performed temporarily!"); try {//The current production line waits and yields a lock (note that only the lock is acquired to allow the lock to be said)//if the Wait () method of an object is called, the current thread must have the monitor (that is, the lock) of the object,//So call Wait () The method must be in a synchronous block or synchronous method (synchronized block or Synchronized method) monitor.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} Meet production conditions, then production, here simply change the current stock curnum + = Neednum; System.out.println ("has produced" + Neednum + "products, the current storage capacity is" + curnum);//Wake Up all threads waiting on this object monitor//Call the Notify () method of an object, The current thread must also have the monitor,//of this object so calling the Notify () method must be done either in a synchronous block or in a synchronous method (synchronized block or Synchronized method). Monitor.notiFyall ();}} Consumption of the specified number of products public void consume (int neednum) {synchronized (monitor) {//test can be consumed while (Curnum < Neednum) {try {//Current consumption The thread waits and yields the lock monitor.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} Satisfy the consumption condition, then carry on the consumption, here simple change current stock quantity Curnum = Neednum;    System.out.println ("already consumed" + Neednum + "products, the current storage capacity is" + curnum);//Wake Up all threads waiting on this object monitor Monitor.notifyall ();}} }//Producer class Producer extends Thread {private int neednum;//number of production products private Godown go Down              Warehouse Producer (int neednum, Godown godown) {this.neednum = Neednum;          This.godown = Godown;          } @Override public void Run () {//production of a specified number of products Godown.produce (neednum);  }}//Consumer class Consumer extends Thread {private int neednum; The number of products produced is private godown godown;              Warehouse Consumer (int neednum, Godown godown) {this.neednum = Neednum; THis.godown = Godown;          } @Override public void Run () {//consume a specified number of products Godown.consume (neednum);   }      }  }

You can also use blocking queues, semaphore, and other means to achieve.

  

Java Interview 13| algorithm

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.