二维数组中的查找
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
public class Solution {
public boolean Find(int [][] array,int target) {
int h = array.length-1;
int l = array[0].length;
int i = 0;
while (h>=0 && i<l) {
if (array[h][i] > target)
h--;
else if (array[h][i] < target)
i++;
else
return true;
}
return false;
}
}
例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
import java.util.*;
import java.util.Map.Entry;
public class Solution {
public boolean duplicate(int numbers[],int length,int duplication) {
if (numbers == null || numbers.length <= 1) {
return false;
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : numbers) {
if (map.containsKey(i))
map.put(i, map.get(i)+1);
else
map.put(i, 1);
}
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Integer, Integer> entry = (Entry<Integer, Integer>)iterator.next();
int key = entry.getKey();
int value = map.get(key);
if (value > 1) {
duplication = key;
return true;
}
}
return false;
}
}
旋转数组的最小数字
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
if (array == null || array.length ==0) {
return 0;
}
for (int l = array.length - 1; l>0; l--) {
if (array[l-1] > array[l]) {
return array[l];
}
}
return 0;
}
}