两数之和2(有序数组)
二分查找:
/**
* 二分查找
* @param arr
* @param target
* @return
*/
public static int[] method(int[] arr,int target){
int n = arr.length;
for (int i = 0; i < n; i++) {
int searchNum = target-arr[i];
int start = i+1;
int end = n-1;
while (start <= end) { // 当start和end相同时,即代表判断当前和要查找的值(伴侣)是否相同
int mid = (start+end)/2;
if (searchNum<arr[mid]){
end = mid-1;
}else if(searchNum>arr[mid]){
start = mid +1;
}else if(searchNum==arr[mid]){
return new int[]{i+1,mid+1};
}
}
}
return new int[]{-1,-1};
}
双指针:
/**
* 双指针效率很高
* @param arr
* @param target
* @return
*/
public static int[] method2(int[] arr,int target){
int n = arr.length;
int left = 0;
int right = n-1;
while (left<right){
if (arr[left]+arr[right] == target) {
return new int[]{left+1,right+1};
}else if(arr[left]+arr[right] >target){
right--;
}else{
left++;
}
}
return new int[]{-1,-1};
}
多数元素
entrySet和进一步迭代器遍历方法:
public static int method(int[] arr){
int n = arr.length;
int targetCount = n/2;
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : arr) {
Integer count = map.getOrDefault(num, 0);
map.put(num,++count);
}
// 可以
// Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator(); // 遍历集合
// while (iterator.hasNext()) {
// Map.Entry<Integer, Integer> next = iterator.next();
// Integer c = next.getValue();
// if (c > targetCount) {
// return next.getKey();
// }
// }
// 也可
Set<Map.Entry<Integer, Integer>> countEntrySet = map.entrySet();
for (Map.Entry<Integer, Integer> entry : countEntrySet) {
if (entry.getValue()>targetCount) {
return entry.getValue();
}
}
return -1;
}
哈希临时保存map迭代法:
public static int majorityElement(int[] nums) {
HashMap<Integer, Integer> mapCount = new HashMap<>();
for (int num : nums) {
Integer count = mapCount.getOrDefault(num, 0);
mapCount.put(num, ++count);
}
Map.Entry<Integer,Integer> tempMap = null;
for (Map.Entry<Integer, Integer> mapCountEntry : mapCount.entrySet()) {
if (tempMap == null || mapCountEntry.getValue() > tempMap.getValue()) {
tempMap = mapCountEntry;
}
}
return tempMap.getKey();
}