一、offer-03 找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入: [2, 3, 1, 0, 2, 5, 3] 输出:2 或 3
题解:
public static int findRepeatNumber(int[] nums) { if (nums.length == 0 || nums == null){ return -1; } //遍历数组,将数组的元素存储至map中 Set<Integer> set = new HashSet<>(); for (int i = 0; i < nums.length; i++) { if (!set.add(nums[i])){ return nums[i]; } } return -1; }二、offer-04 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
现有矩阵 matrix 如下:
[ [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] ] 给定 target = 5,返回 true。
public static boolean findNumberIn2DArray(int[][] matrix, int target) { //判断二维数组 if (matrix == null || matrix.length == 0 || matrix[0].length == 0){ return false; } //从二维数组右上角开始遍历 int row = matrix.length; int column = matrix[0].length; int n=0,m=column-1; while (n < row && m >= 0){ if (target == matrix[n][m]){ return true; }else if (target < matrix[n][m]){ m--; }else { n++; } } return false; }三、offer-05 请实现一个函数,把字符串 s 中的每个空格替换成" "。 示例 1:
输入:s = “We are happy.” 输出:“We are happy.”
public String replaceSpace(String s) { StringBuilder sb = new StringBuilder(); if (s.length() == 0 || s == null){ return sb.toString(); } for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ' '){ sb.append(" "); }else{ sb.append(s.charAt(i)); } } return sb.toString(); }