JAVA interview Selection [Java Algorithm and programming 2]

Source: Internet
Author: User

During the interview, algorithm questions are necessary. Through algorithms, we can see a programmer's programming thinking, examine the design and analysis capabilities for complex problems, and reflect the rigor of the problem. Algorithms are a series of clear instructions for solving problems, that is, they can obtain the required output within a limited period of time for certain standard input. Algorithms often contain repeated steps and comparison or logical judgment. If an algorithm has a defect or is not suitable for a problem, executing the algorithm will not solve the problem. Different algorithms may use different time, space, or efficiency to accomplish the same task. The advantages and disadvantages of an algorithm can be measured by space complexity and time complexity. The quality of an algorithm directly affects the performance of a method call and the overall performance of the software. 6. Read all the names from text files similar to the following, print the duplicate names and number of repetitions, and sort by repetition: 1, 3, 28 2, li Si, 35 3, Zhang San, 28 4, Wang Wu, 35 5, Zhang San, 28 6, Li Si, 35 7, Zhao Liu, 28 8, Tian Qi, the 35 program code is as follows (the answer should be liked by the employer, and the package name should be used by the company. The company's website should be checked in advance before the interview. If you cannot find it, you can also ask on-site questions. Add comments to the implementation idea): package com. huawei. interview; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. util. comparator; import java. util. hashMap; import java. util. iterator; import java. util. map; import java. util. treeSet; publicclass GetNameTest {/*** @ paramargs */public static voidmain (String [] args) {// TODO Auto-generat Ed method stub // InputStream ips = GetNameTest. class. getResourceAsStream ("/com/huawei/interview/info.txt"); // The Code Annotated with the current row and the code of the next row can be, because the info.txt and GetNameTest classes are under the same package, map results = new HashMap (); InputStream ips = GetNameTest. class. getResourceAsStream ("info.txt"); BufferedReader in = newBufferedReader (new InputStreamReader (ips); String line = null; try {while (line = in. readLine ())! = Null) {dealLine (line, results);} sortResults (results);} catch (IOException e) {// TODO Auto-generated catchblock e. printStackTrace () ;}} static class User {public String name; public Integer value; public User (String name, Integervalue) {this. name = name; this. value = value ;}@ Override public booleanequals (Object obj) {// TODO Auto-generated methodstub // the following code is not executed. When adding data to the treeset, equa is not used Ls method. Boolean result = super. equals (obj); System. out. println (result); return result;} private static voidsortResults (Map results) {// TODO Auto-generated method stub TreeSet sortedResults = newTreeSet (new Comparator () {public intcompare (Object o1, Object o2) {// TODOAuto-generated method stub User user1 = (User) o1; User user2 = (User) o2; /* If compareTo returns the result 0, the two objects are considered equal, and the new objects are not added to the Set *. Therefore, the following code cannot be used directly. Otherwise, Other names with the same number cannot be printed. ** // Returnuser1.value-user2.value; // returnuser1.value <user2.value? -1: user1.value = user2.value?; If (user1.value <user2.value) {return-1;} else if (user1.value> user2.value) {return 1;} else {returnuser1.name. compareTo (user2.name) ;}}}); Iterator iterator = results. keySet (). iterator (); while (iterator. hasNext () {String name = (String) iterator. next (); Integer value = (Integer) results. get (name); if (value> 1) {sortedResults. add (newUser (name, value) ;}} printResults (sortedResults);} pri Vate static voidprintResults (TreeSet sortedResults) {Iterator iterator = sortedResults. iterator (); while (iterator. hasNext () {User user = (User) iterator. next (); System. out. println (user. name + ":" + user. value) ;}} public static voiddealLine (String line, Map map) {if (! "". Equals (line. trim () {String [] results = line. split (","); if (results. length = 3) {String name = results [1]; Integer value = (Integer) map. get (name); if (value = null) value = 0; map. put (name, value + 1) ;}}} 7. Write a Singleton. First: full Chinese Mode public classSingleTon {private SingleTon () {}// the instantiation is placed in the static code block, which improves the program execution efficiency, but it may also occupy more space private final static SingleTon instance = new SingleTon (); public static SingleTon getInstance () {return instance ;}} second: hunger mode public classSingleTon {private SingleTon () {} private static instance = null; // newSingleTon (); public static synchronized SingleTongetInstance () {if (instance = null) instance = new S IngleTon (); return instance ;}} method 3: Use enumeration public enum SingleTon {ONE;} method 3: more practical application (in case of SingleTon) public classSequenceGenerator {// The following is the business function code of this class: private int count = 0; public synchronized int getSequence () {++ count ;} // The following code turns this class into the SingleTon private SequenceGenerator () {} private final static instance = newSequenceGenerator (); public static SingleTon getInstance () {return instance ;}} Fourth: public class MemoryDao {Private HashMap map = new HashMap (); publicvoid add (Student stu1) {map. put (SequenceGenerator. getInstance (). getSequence (), stu1);} // change MemoryDao to Singleton mode to ensure that only one instance of a Class exists in a Java application. Generally, the Singleton mode has several forms: the first form: defines a class, and its constructor is private. It has a static private variable, when the class is initialized, a public getInstance method is used to obtain its reference and then call the method. Public class Singleton {private Singleton () {}// define your own instance internally. Isn't it strange? // Note that this is private only for internal calls. private staticSingleton instance = new Singleton (); // a static method is provided for external access to this class, you can directly access public staticSingleton getInstance () {return instance ;}} In the second form: public class Singleton {private static Singleton instance = null; public static synchronized Singleton getInstance () {// This method is better than above. You do not need to generate objects every time. It is only the first time you use this method to generate an instance, which improves the efficiency! If (instance = null) instance = new Singleton (); return instance ;}} other forms: Define a class, its constructor is private, and all methods are static. It is generally considered that the first form is more secure. 8. recursive algorithm question 1 is an integer greater than 0, without loops or local variables. It increments in the order of n, 2n, 4n, and 8n, when the value is greater than 5000, the value is output in the specified order. For example, if n = 1237, the output is 1237,2474, 4948,9896, 9896,4948, 2474,1237. Note: When writing a program, you must first acknowledge the incremental code. After writing the incremental code, then, we will add the descending part. Public static void doubleNum (int n) {System. out. println (n); if (n <= 5000) doubleNum (n * 2); System. out. println (n);} Gaibaota (N) = Gaibaota (N-1) + n 9, recursive algorithm question 2 1st people 10, 2nd people 2 years older than 1st people, recursive, calculate the size of 8th People in recursion mode? Package cn. itcast; import java. util. date; publicclass A1 {public static voidmain (String [] args) {System. out. println (computeAge (8);} public static int computeAge (intn) {if (n = 1) return 10; returncomputeAge (n-1) + 2 ;}} public static voidtoBinary (int n, StringBuffer result) {if (n/2! = 0) toBinary (n/2, result); result. append (n % 2);} 10. What are the methods for sorting? List. Use JAVA to implement a fast sorting. I have only studied Bubble sorting, select sorting, and quick sorting. The following is the code for quick sorting: public class QuickSort {/*** quick sorting ** @ param strDate * @ param left * @ param right */public void quickSort (String [] strDate, int left, int right) {String middle, tempDate; int I, j; I = left; j = right; middle = strDate [(I + j)/2]; do {while (strDate [I]. compareTo (middle) <0 & I <right) I ++; // find the number on the left greater than the median while (strDate [j]. compareTo (middle)> 0 & j> left) j --; // find a number smaller than the median on the right if (I <= j) {// Replace the large number on the left and the small number on the right TempDate = strDate [I]; strDate [I] = strDate [j]; strDate [j] = tempDate; I ++; j --;}} while (I <= j); // when the two are staggered, stop if (I <right) {quickSort (strDate, I, right ); // slave} if (j> left) {quickSort (strDate, left, j );}} /*** @ param args */public static void main (String [] args) {String [] strVoid = newString [] {"11", "66 ", "22", "0", "55", "22", "0", "32"}; QuickSort sort = new QuickSort (); sort. quickSort (strVoid, 0, strVoid. length-1); for (int I = 0; I <strVoid. Length; I ++) {System. out. println (strVoid [I] + "") ;}} 11. array a [n], use java code to reverse the order of array elements // You can also use the following // for (inti = 0, int j =. length-1; whether I <j; I ++, j --) is equivalent to for (int I = 0; I <. length/2; I ++? Importjava. util. arrays; public classSwapDemo {public static void main (String [] args) {int [] a = new int [] {(int) (Math. random () * 1000), (int) (Math. random () * 1000), (int) (Math. random () * 1000), (int) (Math. random () * 1000), (int) (Math. random () * 1000)}; System. out. println (a); System. out. println (Arrays. toString (a); swap (a); System. out. println (Arrays. toString (a);} public static void swap (int a []) {Int len =. length; for (int I = 0; I <len/2; I ++) {int tmp = a [I]; a [I] = a [len-1-i]; a [len-1-i] = tmp ;}} 12. amount conversion: The amount of Arabic numerals is converted to the traditional Chinese format, for example: (¥1011)-> (one thousand and one yuan) output. Code for zero removal: returnsb. reverse (). toString (). replaceAll ("Zero [zhibai]", "zero "). replaceAll ("Zero + ten thousand", "Ten Thousand "). replaceAll ("Zero + RMB", "RMB "). replaceAll ("Zero +", "zero"); public class RenMingBi {/*** @ param args add by zxx, nov 29,200 8 */private static finalchar [] data = new char [] {'0', 'yi', 'er', 'san', 'Ta ', 'wo', 'loan', 'weight'}; private static finalchar [] units = new char [] {'meta ', 'pick', 'handler', 'handler', 'wan', 'handler', 'yie'}; public static voidmain (Str Ing [] args) {// TODOAuto-generated method stub System. out. println (convert (135689123);} public static Stringconvert (int money) {StringBuffersbf = new StringBuffer (); int unit = 0; while (money! = 0) {sbf. insert (0, units [unit ++]); intnumber = money % 10; sbf. insert (0, data [number]); money/= 10;} returnsbf. toString ();}}

Related Article

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.