面试题03.数组中重复的数字
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
思路:先将数组排序,遍历数组比较当前元素和后一个元素是否相等,相等则说明重复跳出循环直接返回当前元素值。
class Solution {
public int findRepeatNumber(int[] nums) {
Arrays.sort(nums);
int i;
for(i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1]){
break;
}
}
return nums[i];
}
}
如果数组中多一半的数都是同一个,则称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
思路:如果该数组只有一个元素是一种特殊情况,直接返回该元素的值。对于其他情况,先排序,遍历该数组,记录元素重复次数,如果次数大于数组长度的一半,则返回当前元素。没找到则返回-1.
class Solution {
public int majorityElement(int[] nums) {
if(nums.length==1){
return nums[0];
}
Arrays.sort(nums);
int count=1;
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1]){
count++;
}else{
count = 1;
}
if(count>nums.length/2){
return nums[i];
}
}
return -1;
}
}
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
扫描二维码关注公众号,回复: 11642441 查看本文章
思路:
从右上角开始走,利用这个顺序关系可以在
O(m+n)
的复杂度下解决这个题:
- 如果当前位置元素比target小,则row++
- 如果当前位置元素比target大,则col--
- 如果相等,返回true
- 如果越界了还没找到,说明不存在,返回false
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0) {
return false;
}
int m = matrix.length, n = matrix[0].length;
int row = 0, col = n - 1;
while(row < m && col >= 0) {
if(matrix[row][col] > target) {
col--;
}else if(matrix[row][col] < target) {
row++;
}else {
return true;
}
}
return false;
}
}
矩形以列表
[x1, y1, x2, y2]
的形式表示,其中(x1, y1)
为左下角的坐标,(x2, y2)
是右上角的坐标。如果相交的面积为正,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。
给出两个矩形,判断它们是否重叠并返回结果。
思路:判断边界条件,我们只需要使第一个矩形不在第二个矩形内部就行了。
前者的x2比后者x1大或者前者的y2比后者的y1大或者前者的x1比后者的x2小或者前者的y1比后者的y2小
class Solution {
public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
if(rec1[0]>=rec2[2]||rec1[1]>=rec2[3]||rec1[2]<=rec2[0]||rec1[3]<=rec2[1])
return false;
return true;
}
}