[toc]
3. 数组中重复的数字
思路:数组数字范围为1-n,统计count[num]即可
class Solution {
public int findRepeatNumber(int[] nums) {
int n = nums.length;
int[] count = new int[n];
for(int num: nums) {
if(count[num] != 0 ){
return num;
} else {
count[num] ++;
}
}
return -1;
}
}
4. 二维数组中的查找
思路: 从左下角开始查找
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix.length == 0)
return false;
int m = matrix.length, n = matrix[0].length;
int i = m - 1, j = 0;
while(i >= 0 && j < n) {
if(target > matrix[i][j]) {
j++;
} else if(target < matrix[i][j]) {
i--;
} else {
return true;
}
}
return false;
}
}
5. 替换空格
思路:
a)找出空格数量,计算结果的长度
b)倒序添加02%
class Solution {
public String replaceSpace(String s) {
if(s.length() == 0)
return s;
char[] chars = s.toCharArray();
int spaceCount = 0;
for(char c : chars) {
if(c == ' ')
spaceCount++;
}
char[] res = new char[chars.length + spaceCount * 2];
int index = res.length - 1;
for(int i = chars.length - 1; i >= 0;i--){
if(chars[i] == ' ') {
res[index] = '0';
res[index - 1] = '2';
res[index - 2] = '%';
index = index - 3;
} else {
res[index] = chars[i];
index --;
}
}
return String.valueOf(res);
}
}
29. 顺时针打印矩阵
关键点: 注意从右到左、从下到上 进行check
class Solution {
public int[] spiralOrder(int[][] matrix) {
int m = matrix.length;
if(m == 0) {
return new int[]{};
}
int n = matrix[0].length;
int[] res = new int[m * n];
int index = 0;
int left = 0, right = n -1 , top = 0 , bottom = m - 1;
while(left <= right && top <= bottom) {
// 左到右
for(int i = left;i <= right;i ++) {
res[index++] = matrix[top][i];
}
top++;
// 上到下
for(int i = top;i <= bottom;i++){
res[index++] = matrix[i][right];
}
right--;
// !!!!!
if(top <= bottom) {
for(int i = right;i >= left;i--) {
res[index++] = matrix[bottom][i];
}
bottom--;
}
if(left <= right) {
for(int i = bottom;i >= top;i--) {
res[index++] = matrix[i][left];
}
left++;
}
}
return res;
}
}
50. 第一个只出现一次的字符位置
思路:因为字符,ASCII 范围0-128,使用count方法
class Solution {
public char firstUniqChar(String s) {
if(s.length() == 0)
return ' ';
int[] counts = new int[128];
for(char c: s.toCharArray()) {
counts[c - '0']++;
}
for(char c: s.toCharArray()) {
if(counts[c - '0'] == 1) {
return c;
}
}
return ' ';
}
}