给定一个目标和,找出给定数组中是否有一对元素和它相加 import java.util.HashMap; 公共类目标 { 公共静态无效哈希(int[]a,int-sum) { HashMap=newHashMap(); int i; 对于(i=0;i
我想知道是否有比上述解决方案更好、更有效的解决方案。这个问题的复杂性是n。我能做得更好吗?您的实现丢失了重复对给定一个目标和,找出给定数组中是否有一对元素和它相加 import java.util.HashMap; 公共类目标 { 公共静态无效哈希(int[]a,int-sum) { HashMap=newHashMap(); int i; 对于(i=0;i,java,hashmap,complexity-theory,Java,Hashmap,Complexity Theory,我想知道是否有比上述解决方案更好、更有效的解决方案。这个问题的复杂性是n。我能做得更好吗?您的实现丢失了重复对 你可以 对数组进行排序 从一开始就对每个元素进行迭代 计算所需的补码(总和-元素) 执行反向二进制搜索(从排序数组的末尾)以查找该精确值 如果找到,请同时移除两个 它归结为一个观察结果,即在对元素进行排序后: n1
你可以
- 计算所需的补码(总和-元素)
- 执行反向二进制搜索(从排序数组的末尾)以查找该精确值
- 如果找到,请同时移除两个
n1
最有可能的一对从两端到中间对称出现。现在,最坏的情况仍然很糟糕,但至少您没有哈希表开销正如我所评论的,您的解决方案不是O(N),因为containsValue搜索存储在HashMap中的所有值。为了解决这个问题,我使用您的解决方案采用了不同的方法:
n1 < n2 < n3 < n4 < n5 < n6
对于这个问题,我有以下解决方案。时间复杂度应该是O(N),因为HashMap操作put、get和keySet是O(1)
import java.util.HashMap;
导入java.util.Map;
/**
*在给定目标和的数组中查找一对数字
*
*
*/
公共类金融机构{
公共静态void findSumsForTarget(int[]输入,int目标)
{
//只需打印它,而不是返回
Map myMap=populateMap(输入);
//迭代密钥集
for(整数currKey:myMap.keySet()){
//找出差异
整数差=目标-当前键;
//检查地图中是否存在差异
字符串diffMapValue=myMap.get(diff);
if(diffMapValue!=null)
{
//总和存在
String output=“目标“+target+”的部分之和为“+currKey+”和“+diff”;
系统输出打印项次(输出);
return;//退出;我们完成了-除非我们想要所有可能的对和排列
}
//否则
//继续找
}
System.out.println(“未找到匹配项!”);
}
私有静态映射populateMap(int[]输入)
{
Map myMap=newhashmap();
for(int i=0;i
解决方案:O(n)时间和O(log(n))空间
公共静态布尔数组\u find(整数[]a,整数X)
{
布尔值[]b=新的布尔值[X];
int i;
对于(i=0;i=0&&temppublicstaticvoidhash1)(int[]a,int-num){
数组。排序(a);
//打印阵列(a);
int-top=0;
int bott=a.length-1;
而(顶部<底部){
while(a[bott]>num)
博特--;
整数和=a[顶部]+a[底部];
如果(总和=num){
System.out.println(“Pair”+a[top]+“”+a[bott]);
top++;
博特--;
}
如果(总和数值)
博特--;
}
}
递归地从给定数组中查找其和为目标和的子集
public static void hash1(int[] a, int num) {
Arrays.sort(a);
// printArray(a);
int top = 0;
int bott = a.length - 1;
while (top < bott) {
while (a[bott] > num)
bott--;
int sum = a[top] + a[bott];
if (sum == num) {
System.out.println("Pair " + a[top] + " " + a[bott]);
top++;
bott--;
}
if (sum < num)
top++;
if (sum > num)
bott--;
}
}
import java.util.ArrayList;
导入java.util.HashSet;
导入java.util.List;
导入java.util.Set;
公共班机{
public static Set=new HashSet();
公共静态void main(字符串[]args){
int[]biggerray={1,2,1,1};
int targetedSum=3;
findSubset(Biggerray、targetedSum);
}
公共静态void findSubset(int[]biggerray,int targetedSum){
for(int i=0;itargetedSum)
继续;
其他的
添加(Biggerray[i]);
if(i+1 public static void newVersion(int[] a, int sum){
HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();
for (int i= 0; i< a.length; i++) {
map.put(sum - a[i], true);
}
for (int i = 0; i < a.length; i++) {
if (map.containsKey(a[i]) && map.get(a[i])) {
System.out.println("("+(sum-a[i])+","+a[i]+")");
map.put(a[i], false);
map.put(sum-a[i], false);
}
}
}
* O(N) for the first looping
* O(N) * (O(1) + O(1)) for the second loop and the containsValue and get.
* Finally: O(N) + O(N) .:. O(N) solution,
import java.util.HashMap;
import java.util.Map;
/**
* Find a pair of numbers in an array given a target sum
*
*
*/
public class FindNums {
public static void findSumsForTarget(int[] input, int target)
{
// just print it instead of returning
Map<Integer, String> myMap = populateMap(input);
// iterate over key set
for (Integer currKey : myMap.keySet()) {
// find the diff
Integer diff = target - currKey;
// check if diff exists in the map
String diffMapValue = myMap.get(diff);
if(diffMapValue!=null)
{
// sum exists
String output = "Sum of parts for target " + target + " are " + currKey + " and " + diff;
System.out.println(output);
return; // exit; we're done - unless we wanted all the possible pairs and permutations
}
// else
// keep looking
}
System.out.println("No matches found!");
}
private static Map<Integer, String> populateMap(int[] input)
{
Map<Integer,String> myMap = new HashMap<Integer,String>();
for (int i = 0; i < input.length; i++) {
String currInputVal = myMap.get(input[i]);
if(currInputVal!=null) // value already exists
{
// append current index location to value
currInputVal = currInputVal + ", " + i;
// do a put with the updated value
myMap.put(input[i], currInputVal);
}
else
{
myMap.put(input[i], Integer.toString(i)); // first argument is autoboxed to Integer class
}
}
return myMap;
}
// test it out!
public static void main(String[] args)
{
int[] input1 = {2,3,8,12,1,4,7,3,8,22};
int[] input2 = {1,2,3,4,5,6,7,8,9,10};
int[] input3 = {2,-3,8,12,1,4,7,3,8,22};
int target1 = 19;
int target2 = 16;
// test
FindNums.findSumsForTarget(input1, target1);
FindNums.findSumsForTarget(input1, -1);
FindNums.findSumsForTarget(input2, target2);
FindNums.findSumsForTarget(input3, target1);
}
}
public static boolean array_find(Integer[] a, int X)
{
boolean[] b = new boolean[X];
int i;
for (i=0;i<a.length;i++){
int temp = X-a[i];
if(temp >= 0 && temp < X) //make sure you are in the bound or b
b[temp]=true;
}
for (i=0;i<a.length;i++)
if(a[i]<X && b[a[i]]) return true;
return false;
}
import java.util.*;
import java.io.*;
class hashsum
{
public static void main(String arg[])throws IOException
{
HashMap h1=new HashMap();
h1.put("1st",new Integer(10));
h1.put("2nd",new Integer(24));
h1.put("3rd",new Integer(12));
h1.put("4th",new Integer(9));
h1.put("5th",new Integer(43));
h1.put("6th",new Integer(13));
h1.put("7th",new Integer(5));
h1.put("8th",new Integer(32));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no.");
int no=Integer.parseInt(br.readLine());
Iterator i=h1.entrySet().iterator();
boolean flag=false;
while(i.hasNext())
{
Map.Entry e1=(Map.Entry)i.next();
Integer n1=(Integer)e1.getValue();
Iterator j=h1.entrySet().iterator();
while(j.hasNext())
{
Map.Entry e2=(Map.Entry)j.next();
Integer n2=(Integer)e2.getValue();
if(no==(n1+n2))
{
System.out.println("Pair of elements:"+n1 +" "+n2);
flag=true;
}
}
}
if(flag==false)
System.out.println("No pairs");
}
}
public static void hash1(int[] a, int num) {
Arrays.sort(a);
// printArray(a);
int top = 0;
int bott = a.length - 1;
while (top < bott) {
while (a[bott] > num)
bott--;
int sum = a[top] + a[bott];
if (sum == num) {
System.out.println("Pair " + a[top] + " " + a[bott]);
top++;
bott--;
}
if (sum < num)
top++;
if (sum > num)
bott--;
}
}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static Set<List<Integer>> set = new HashSet<>();
public static void main(String[] args) {
int[] biggerArray = {1, 2, 1, 1};
int targetedSum = 3;
findSubset(biggerArray, targetedSum);
}
public static void findSubset(int[] biggerArray, int targetedSum) {
for (int i = 0; i < biggerArray.length; i++) {
List<Integer> subset = new ArrayList<>();
if (biggerArray[i] > targetedSum)
continue;
else
subset.add(biggerArray[i]);
if (i + 1 < biggerArray.length)
find(subset, i, biggerArray, targetedSum, i);
}
System.out.println(set);
}
public static List<Integer> find(List<Integer> subset, int startIndex, final int[] biggerArray, final int targetedSum, final int skipIndex) {
if (skipIndex == startIndex) {
find(subset, startIndex + 1, biggerArray, targetedSum, skipIndex);
return null;
}
int subsetSum = findSumOfList(subset);
int remainedSum = targetedSum - subsetSum;
int i = startIndex;
if (remainedSum == 0) {
set.add(subset);
return null;
}
if ((startIndex < biggerArray.length) && (biggerArray[startIndex] == remainedSum)) {
List<Integer> temp = new ArrayList<Integer>(subset);
temp.add(biggerArray[i]);
set.add(temp);
}
else if ((startIndex < biggerArray.length) && (biggerArray[startIndex] < remainedSum)) {
while (i + 1 <= biggerArray.length) {
List<Integer> temp = new ArrayList<Integer>(subset);
if (i != skipIndex) {
temp.add(biggerArray[i]);
find(temp, ++i, biggerArray, targetedSum, skipIndex);
}
else {
i = i + 1;
}
}
}
else if ((startIndex < biggerArray.length) && (biggerArray[startIndex] > remainedSum)) {
find(subset, ++i, biggerArray, targetedSum, skipIndex);
}
return null;
}
public static int findSumOfList(List<Integer> list) {
int i = 0;
for (int j : list) {
i = i + j;
}
return i;
}
}
public static void matchingTargetSumPair(int[] input, int target){
Map<Integer, Integer> targetMap = new HashMap<Integer, Integer>();
for(int i=0; i<input.length; i++){
targetMap.put(input[i],target - input[i]);
if(targetMap.containsKey(target - input[i])){
System.out.println("Mathcing Pair: "+(target - input[i])+" , "+input[i]);
}
}
}
public static void main(String[] args) {
int[] targetInput = {1,2,4,5,8,12};
int target = 9;
matchingTargetSumPair(targetInput, target);
}
import java.util.*;
class findElementPairSum{
public static void main(String[] args){
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sum key: ");
int sum=sc.nextInt();
for(int i=0; i<10; i++){
int x = sc.nextInt();
if(!hm.containsKey(sum-x)){
hm.put(x, 1);
} else {
System.out.println("Array contains two elements with sum equals to: "+sum);
break;
}
}
}
}