【问题标题】:Two different numbers in an array which their sum equals to a given value数组中的两个不同数字,它们的和等于给定值
【发布时间】:2015-08-23 07:03:17
【问题描述】:

给定一个数组,我们知道它的大小以及其中可以包含的数字范围。在数组中找到两个元素的总和为给定值。有一个经典版本的算法 使用哈希映射将 O(n) 作为时间复杂度,将 O(K) 作为空间复杂度(K 是整数的范围)。如果我们想找到不同的元素怎么办 总和到那个给定的数字(对于相同的元素它不起作用)。另外,程序只检查是否至少有 一种组合,它不需要找到所有可能的组合。

【问题讨论】:

  • 你只需要忽略所有大小为sum / 2的元素。
  • 请添加您的代码
  • 这看起来像是家庭作业
  • 您的问题是什么?不清楚你在问什么。
  • @Chad - 你试过我的解决方案了吗?如果有效,请接受答案并投票!

标签: arrays algorithm


【解决方案1】:

使用python在带有索引的数组中搜索并打印给定数量的元素总和

list1 = [1,2,3,5]
tmp = list1.copy()
print(tmp)
inp = int(input("enter value equal to sum"))
for i in list1:
    for j in tmp:
        add = i+j
        if add == inp:
            print (list1.index(i)) #printing the index first val
            print (tmp.index(j)) #printing the index second val
            print ("value found",add,i,j)
            break

    #if add ==inp:  '''if uncomment this when it found the first occurance it breaks'''
    #    print("out")
    #    break

【讨论】:

    【解决方案2】:

    这里是 O(n) 解决方案,用于找到总和为预期目标的数组的第一对索引。该解决方案将在找到前 2 个总和为目标的索引时停止,如果您需要所有加起来为目标的对,那么您可以使用 ArrayList 甚至是 Map,处理完整的数组和将其与所有索引对一起返回。有一个明显的假设,即 Map 的 hashcode 函数非常好,并且没有太多的冲突,因此 map 操作在 O(1) 时间内执行。

    添加两个索引值不相同的条件应该为您提供成对不同数字的解决方案。

    import java.util.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            int[] array = new int[] {1,2,4,7,12,67,12,5,9,1,10};
            System.out.println(Arrays.toString(sum(array, 68)));
        }
    
        public static int[] sum(int[] array, int target) {
            int[] result = new int[2];
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            // n iterations
            for (int index = 0; index < array.length; index++) {
                // constant
                if (map.containsKey(target - array[index])
                       && array[index] != array[map.get(target - array[index])]) {
                    result[1] = index;
                    // constant
                    result[0] = map.get(target - array[index]);
                    return result;
                }
                // constant
                map.put(array[index], index);
            }
            return result;
        }
    }
    

    【讨论】:

      【解决方案3】:

      BST 应该可以工作。

      1. 将数组排序为 BST。
      2. while(当前节点不是root,进行中序遍历)
        • 对于当前节点,检查:
        • 如果总和大于当前值
        • 如果数组中有一项满足求和条件
        • 使下一项按顺序遍历当前节点

      第 1 步是 O(nlogn) 第 2 步是 O(n/2 logn)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-07
        • 2012-01-22
        • 1970-01-01
        • 2017-10-07
        • 2014-10-17
        • 1970-01-01
        相关资源
        最近更新 更多