package jz.bm;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class bm5 {
/**
* BM50 两数之和
*/
public int[] twoSum (int[] numbers, int target) {
int[] res = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
res[0] = map.get(target - numbers[i]) + 1;
res[1] = i + 1;
return res;
} else {
map.put(numbers[i], i);
}
}
return res;
}
/**
* BM51 数组中出现次数超过一半的数字
*/
public int MoreThanHalfNum_Solution(int [] array) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < array.length; i++) {
if (map.containsKey(array[i])) {
map.put(array[i], map.get(array[i]) + 1);
} else {
map.put(array[i], 1);
}
if (map.get(array[i]) > array.length / 2) {
return array[i];
}
}
return array[0];
}
/**
* BM52 数组中只出现一次的两个数字
*/
public int[] FindNumsAppearOnce (int[] array) {
int[] res = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
for (int k : array) {
if (map.containsKey(k)) {
map.put(k, 2);
} else {
map.put(k, 1);
}
}
ArrayList<Integer> list = new ArrayList<>();
for (int j : array) {
if (map.get(j) == 1) {
list.add(j);
}
}
res[0] = Math.min(list.get(0), list.get(1));
res[1] = Math.max(list.get(0), list.get(1));
return res;
}
/**
* BM53 缺失的第一个正整数
*/
public int minNumberDisappeared (int[] nums) {
Arrays.sort(nums);
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 1; i < Integer.MAX_VALUE; i++) {
if (!map.containsKey(i)) {
return i;
}
}
return -1;
}
/**
* BM54 三数之和
*/
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
Arrays.sort(num);
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < num.length; i++) {
map.put(num[i], i);
}
int a, b, c;
for (int i = 0; i < num.length; i = map.get(a) + 1) {
a = num[i];
for (int j = i + 1; j < num.length; j = map.get(b) + 1) {
b = num[j];
c = -a - b;
if (map.containsKey(c) && map.get(c) > j) {
ArrayList<Integer> list = new ArrayList<>();
list.add(a);
list.add(b);
list.add(c);
lists.add(list);
}
}
}
return lists;
}
}
算法练习(4):牛客在线编程05 哈希
猜你喜欢
转载自blog.csdn.net/weixin_42774617/article/details/132050457
今日推荐
周排行