National Day and Mid-Autumn Festival Special (7) 20 Common Programming Interview Questions for Java Software Engineers

Insert image description here

The following are common programming interview questions for intermediate and senior Java software engineers. There are 20 questions in total.

  1. How to determine whether an array is an ordered array?
    Answer: You can compare the sizes of adjacent elements through one traversal. If adjacent elements are found to be in the wrong size order, the array is not ordered.
public boolean isSortedArray(int[] nums) {
    
      
   for (int i = 0; i < nums.length - 1; i++) {
    
      
       if (nums[i] > nums[i + 1]) {
    
      
           return false;  
       }  
   }  
   return true;  
}
  1. How to remove duplicate elements from an ordered array?
    Answer: Adjacent duplicate elements can be deleted through one traversal.
public int[] removeDuplicates(int[] nums) {
    
      
   if (nums == null || nums.length == 0) {
    
      
       return null;  
   }  
   int i = 0;  
   for (int j = 0; j < nums.length; j++) {
    
      
       if (i == 0 || nums[j]!= nums[i]) {
    
      
           nums[i++] = nums[j];  
       }  
   }  
   int[] result = new int[i];  
   System.arraycopy(nums, 0, result, 0, i);  
   return result;  
}
  1. How to merge two sorted arrays?
    Answer: Two sorted arrays can be merged into a new sorted array in one pass.
public int[] mergeTwoSortedArrays(int[] nums1, int[] nums2) {
    
      
   int[] result = new int[nums1.length + nums2.length];  
   int i = 0, j = 0, k = 0;  
   while (i < nums1.length && j < nums2.length) {
    
      
       if (nums1[i] < nums2[j]) {
    
      
           result[k++] = nums1[i++];  
       } else {
    
      
           result[k++] = nums2[j++];  
       }  
   }  
   while (i < nums1.length) {
    
      
       result[k++] = nums1[i++];  
   }  
   while (j < nums2.length) {
    
      
       result[k++] = nums2[j++];  
   }  
   return result;  
}
  1. How to reverse an array?
    Answer: You can flip each element of the array in one pass.
public void reverseArray(int[] nums) {
    
      
   for (int i = 0; i < nums.length; i++) {
    
      
       int temp = nums[i];  
       nums[i] = nums[nums.length - 1 - i];  
       nums[nums.length - 1 - i] = temp;  
   }  
}
  1. How to calculate the average of an array?
    Answer: Add all the elements of the array and divide by the length of the array.
public double averageArray(int[] nums) {
    
      
   long sum = 0;  
   for (int num : nums) {
    
      
       sum += num;  
   }  
   return (double) sum / nums.length;  
}
  1. How to calculate the median of an array?
    Answer: After sorting the array, find the middle element. If the array length is even, then the average of the middle two elements is the median.
public double medianArray(int[] nums) {
    
      
   Arrays.sort(nums);  
   int length = nums.length;  
   if (length % 2 == 0) {
    
      
       return (double) (nums[length / 2 - 1] + nums[length / 2]) / 2.0;  
   } else {
    
      
       return (double) nums[length / 2];  
   }  
}
  1. How to calculate the mode of an array?
    Answer: You can count the number of occurrences of each element through one traversal. The element that occurs most often is the mode.
public int mostCommon(int[] nums) {
    
      
   int[] count = new int[101];  
   for (int num : nums) {
    
      
       count[num]++;  
   }  
   int max = 0;  
   int res

   for (int i = 0; i < 101; i++) {
    
        
       if (count[i] > max) {
    
        
           max = count[i];    
           res = i;    
       }    
   }    
   return res;    
}
  1. How to calculate the variance of an array?
    Answer: Subtract all elements of the array, square them, then sum them, and finally divide them by the length of the array.
public double varianceArray(int[] nums) {
    
        
   long sum = 0;    
   for (int num : nums) {
    
        
       sum += num;    
   }    
   double mean = (double) sum / nums.length;    
   double sumSqr = 0;    
   for (int num : nums) {
    
        
       double d = num - mean;    
       sumSqr += d * d;    
   }    
   return sumSqr / nums.length;    
}
  1. How to calculate the standard deviation of an array?
    Answer: After calculating the variance, take the square root of the variance.
public double standardDeviationArray(int[] nums) {
    
        
   double variance = varianceArray(nums);    
   return Math.sqrt(variance);    
}
  1. How to determine whether a string is a palindrome string?
    Answer: You can use two traversals to compare whether the first half and the second half of the string are the same.
public boolean isPalindrome(String s) {
    
        
   int i = 0;    
   int j = s.length() - 1;    
   while (i < j) {
    
        
       if (s.charAt(i)!= s.charAt(j)) {
    
        
           return false;    
       }    
       i++;    
       j--;    
   }    
   return true;    
}
  1. How to remove all duplicate characters from a string?
    Answer: You can add each character in the string to a new character array in a single pass, or if the character is not present in the character array, add the character to the character array. Finally convert the character array to string.
public String removeDuplicates(String s) {
    
        
   if (s == null || s.length() == 0) {
    
        
       return null;    
   }    
   char[] chars = new char[s.length()];    
   for (int i = 0; i < s.length(); i++) {
    
        
       if (chars[i]!= s.charAt(i)) {
    
        
           chars[chars.length - 1] = s.charAt(i);    
       }    
   }    
   return new String(chars);    
}
  1. How to merge two strings?
    Answer: You can combine characters from two strings into a new string in one pass.
public String mergeStrings(String s1, String s2) {
    
        
   if (s1 == null) {
    
        
       return s2;    
   }    
   if (s2 == null) {
    
        
       return s1;    
   }    
   StringBuilder sb = new StringBuilder();    
   for (int i = 0; i < Math.max(s1.length(), s2.length()); i++) {
    
        
       char c1 = (i < s1.length())? s1.charAt(i) : '\0';    
       char c2 = (i < s2.length())? s2.charAt(i) : '\0';    
       sb.append(c1);    
       sb.append(c2);    
   }    
   return sb.toString();    
}
  1. How to calculate the edit distance of two strings?
    Answer: You can use dynamic programming to calculate the minimum number of operations required to convert one string to another.
public int editDistance(String s1, String s2) {
    
      
   int m = s1.length();  
   int n = s2.length();  
   int[][] dp = new int[m + 1][n + 1];
   for (int i = 0; i <= m; i++) {
    
      
       for (int j = 0; j <= n; j++) {
    
      
           if (i == 0) {
    
      
               dp[i][j] = j;  
           } else if (j == 0) {
    
      
               dp[i][j] = i;  
           } else if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
    
      
               dp[i][j] = dp[i - 1][j - 1];  
           } else {
    
      
               dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1;  
           }  
       }  
   }  
   return dp[m][n];  
}
  1. How to implement a singleton pattern?
    Answer: You can use the lazy style and the hungry style to implement the singleton pattern.
    Lazy man style:
public class Singleton {
    
      
   private static Singleton instance;
   private Singleton() {
    
      
   }
   public static Singleton getInstance() {
    
      
       if (instance == null) {
    
      
           instance = new Singleton();  
       }  
       return instance;  
   }  
}

Hungry Chinese style:

public class Singleton {
    
      
   private static final Singleton instance = new Singleton();
   private Singleton() {
    
      
   }
   public static Singleton getInstance() {
    
      
       return instance;  
   }  
}
  1. How to implement a factory pattern?
    Answer: Create a factory class and create corresponding objects based on the parameters passed in.
public class Factory {
    
      
   public static void main(String[] args) {
    
      
       Product productA = factory.createProductA();  
       Product productB = factory.createProductB();
       productA.display();  
       productB.display();  
   }
   public static Product createProductA() {
    
      
       return new ProductA();  
   }
   public static Product createProductB() {
    
      
       return new ProductB();  
   }  
}
abstract class Product {
    
      
   public abstract void display();  
}
class ProductA extends Product {
    
      
   public void display() {
    
      
       System.out.println("Product A");  
   }  
}
class ProductB extends Product {
    
      
   public void display() {
    
      
       System.out.println("Product B");  
   }  
}
  1. How to implement an observer pattern?
    Answer: Create an observer interface, a subject interface, and concrete observer and subject classes. Notify all observers when the topic state changes.
public class ObserverPattern {
    
      
   public static void main(String[] args) {
    
      
       Subject subject = new Subject();  
       Observer observer1 = new ConcreteObserver(subject);  
       Observer observer2 = new ConcreteObserver(subject);
       subject.addObserver(observer1);  
       subject.addObserver(observer2);
       subject.notifyObservers();  
   }
   public static interface Subject {
    
      
       void addObserver(Observer observer);  
       void removeObserver(Observer observer);  
       void notifyObservers();  
   }
   public static interface Observer {
    
      
       void update(String message);  
   }
   public static class ConcreteObserver implements Observer {
    
      
       private Subject subject;
       public ConcreteObserver(Subject subject) {
    
      
           this.subject = subject;  
       }
       @Override  
       public void update(String message) {
    
      
           System.out.println("Received: " + message);  
       }  
   }
   public static class ConcreteSubject implements Subject {
    
      
       private List<Observer> observers;
       public ConcreteSubject() {
    
      
           observers = new ArrayList<>();  
       }
       @Override  
       public void addObserver(Observer observer) {
    
      
           observers.add(observer);  
       }
       @Override  
       public void removeObserver(Observer observer) {
    
      
           observers.remove(observer);  
       }
       @Override  
       public void notifyObservers() {
    
      
           for (Observer observer : observers) {
    
      
               observer.update("Hello, World!");  
           }  
       }  
   }  
}
  1. How to implement a strategy pattern?
    Answer: Create a strategy interface and specific strategy class. At runtime, appropriate strategies are selected for execution based on different situations.
public class StrategyPattern {
    
      
   public static void main(String[] args) {
    
      
       Strategy strategy = new DefaultStrategy();  
       strategy.execute();
       strategy = new CustomStrategy();  
       strategy.execute();  
   }
   public static interface Strategy {
    
      
       void execute();  
   }
   public static class DefaultStrategy implements Strategy {
    
      
       @Override  
       public void execute() {
    
      
           System.out.println("Default strategy");  
       }  
   }
   public static class CustomStrategy implements Strategy {
    
      
       @Override  
       public void execute() {
    
      
           System.out.println("Custom strategy");  
       }  
   }  
}
  1. How to implement an adapter pattern?

Implementing the adapter pattern requires the following steps:

  1. Determine the target interface: First, you need to clarify the target interface to be adapted, that is, the interface that the client expects to use. This interface can be an existing interface or an abstract interface.
  2. Create an adapter class: Create an adapter class that will implement the target interface and contain an instance of the adapted class inside it. The adapter class needs to implement all methods of the target interface and call the corresponding methods of the adapted class in these methods.
  3. Implement the target interface: Implement all methods of the target interface in the adapter class, which will be used by the client. When implementing these methods, you need to pass the parameters passed in by the client to the corresponding methods of the adapted class, and return the results returned by the methods of the adapted class to the client.
    Here is a simple implementation example of the adapter pattern:
// 目标接口  
public interface Target {
    
      
   void request();  
}
// 被适配的类  
public class Adaptee {
    
      
   public void specificRequest() {
    
      
       System.out.println("被适配的类的方法被调用");  
   }  
}
// 适配器类  
public class Adapter implements Target {
    
      
   private Adaptee adaptee;
   public Adapter(Adaptee adaptee) {
    
      
       this.adaptee = adaptee;  
   }
   @Override  
   public void request() {
    
      
       adaptee.specificRequest();  
   }  
}
// 客户端代码  
public class Client {
    
      
   public static void main(String[] args) {
    
      
       Adaptee adaptee = new Adaptee();  
       Target target = new Adapter(adaptee);  
       target.request();  
   }  
}

In this example, Targetit is the target interface, Adapteethe class being adapted, Adapterand the adapter class. The adapter class Adapterimplements the target interface Targetand calls the method of request()the adapted class in its method . The client code uses the adapter class through the target interface to implement the call to the adapted class .AdapteespecificRequest()TargetAdapterAdaptee

  1. Title: Tower of Hanoi problem
    Problem description: Please use Java to implement a solution to solve the Tower of Hanoi problem. The Tower of Hanoi is a classic recursive problem that requires moving N disks on a pole from one side to the other according to certain rules.
    Answer: The following is a sample code that implements the Tower of Hanoi problem in Java:
public class HanoiTower {
    
      
   public static void main(String[] args) {
    
      
       int n = 3; // 设置盘子的数量  
       hanoi(n, 'A', 'B', 'C');  
   }
   /**  
    * 汉诺塔递归方法  
    * @param n 盘子数量  
    * @param from 源柱子  
    * @param auxiliary 辅助柱子  
    * @param to 目标柱子  
    */  
   public static void hanoi(int n, char from, char auxiliary, char to) {
    
      
       if (n == 1) {
    
     // 当只有一个盘子时,直接从源柱子移动到目标柱子  
           System.out.println("Move disk 1 from " + from + " to " + to);  
       } else {
    
      
           // 将 n-1 个盘子从源柱子借助目标柱子移动到辅助柱子  
           hanoi(n - 1, from, to, auxiliary);  
           // 将第 n 个盘子从源柱子移动到目标柱子  
           System.out.println("Move disk " + n + " from " + from + " to " + to);  
           // 将 n-1 个盘子从辅助柱子借助源柱子移动到目标柱子  
           hanoi(n - 1, auxiliary, from, to);  
       }  
   }  
}
  1. Title: Shopping cart class
    Problem description: Please design a shopping cart class, including functions such as adding products, deleting products, calculating total price, etc.
    Answer: The following is a simple shopping cart class implementation:
public class ShoppingCart {
    
      
   private ArrayList<Item> items;
   public ShoppingCart() {
    
      
       items = new ArrayList<>();  
   }
   /**  
    * 向购物车添加商品  
    * @param item 商品对象  
    */  
   public void addItem(Item item) {
    
      
       for (int i = 0; i < items.size(); i++) {
    
      
           if (items.get(i) == item) {
    
      
               items.set(i, item);  
               return;  
           }  
       }  
       items.add(item);  
   }
   /**  
    * 从购物车中删除商品  
    * @param item 商品对象  
    * @return 是否成功删除  
    */  
   public boolean removeItem(Item item) {
    
      
       for (int i = 0; i < items.size(); i++) {
    
      
           if (items.get(i) == item) {
    
      
               items.remove(i);  
               return true;  
           }  
       }  
       return false;  
   }
   /**  
    * 计算购物车中商品的总价  
    * @return 总价  
    */  
   public double calculateTotal() {
    
      
       double total = 0;  
       for (Item item : items) {
    
      
           total += item.getPrice();  
       }  
       return total;  
   }  
}

The shopping cart class uses an ArrayList to store product objects. The methods of adding products, deleting products and calculating the total price respectively traverse the ArrayList to complete the corresponding operations.

Guess you like

Origin blog.csdn.net/superdangbo/article/details/133514500