Java interview questions ------ two-dimensional array of find, replace spaces

reward

  • 1. Find an array of such thinking
  • 2.StringBulider this method, compared to the terms of StringBuffer, it has the disadvantage of not thread-safe, but the speed was much faster
  • 3. The number of elements in the array are fixed, the length of the array is a constant value, it is used arr.lengthto represent the length; however, in the set, the collection of elements is too complicated, so the use of list.length()the expression

1. Find a two-dimensional array

In a two-dimensional array of n * m, each row from left to right in order of ascending sort, to sort each column from top to bottom in increasing order. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer

Analysis: There are characteristics of the array can know the top right corner of the data has the right smaller than him, bigger than the left half of his property can take to narrow the scope to determine whether the target

Example:
existing matrix multiplied as follows:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
          if(matrix == null||matrix.length==0||matrix[0].length==0){
              return false;
          }
          int lie = matrix[0].length -1;
          int hang = matrix.length;
          int row = 0;
          int column = lie;
          while(column >=0 && row < hang ){
              int shu = matrix[row][column];
              if(shu==target){
                  return true;
              }else if(shu<target){
                  row++;
              }else{
                  column--;
              }
          } 
          return false;   
    }
}

2. Replace spaces

Please implement a function, replace each space in the string s to "20%."

输入:s = "We are happy." 输出:"We%20are%20happy."

StringBuilder use features, the first string into the characters one by one traverse encounter spaces to "% 20" characters normally add

class Solution {
    public String replaceSpace(String s) {
        StringBuilder sb = new StringBuilder();
        int chang = s.length();
        for(int i=0;i<chang;i++){
            char c = s.charAt(i);
            if(c==' '){
                sb.append("%20");
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
Published 87 original articles · won praise 7 · views 5025

Guess you like

Origin blog.csdn.net/y18791050779/article/details/105061593
Recommended