Trip.com W2D1
剑指offer 第一天
03.找出数组中重复的数字。
我的思路:遍历数组,找到一个数相同并返回
题解思路:使用哈希表(Hashset),代码如下
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> dic = new HashSet<>();
for(int num : nums) {
if(dic.contains(num)) {
return num;
}
dic.add(num);
}
return -1;
}
}
04.二维数组的查找
我的思路:从一个角开始进行遍历
题解思路:右上角开始,规定只能向左或向下移动。如果向左移动,元素在减小,如果向下移动,元素在增大,这样的话我们就可以根据当前位置的元素和 target 的相对大小来判断应该往哪移动,不断接近从而找到 target 的位置。
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return false;
}
int m = matrix.length, n = matrix[0].length;
int i = 0, j = n - 1;
while (i < m && j >= 0) {
if (matrix[i][j] == target) {
return true;
} if (matrix[i][j] < target) {
i++;
} else {
j--; }
}
return false;
}
}