1. 程式人生 > >在給定的陣列中找出兩個元素和為給定值的所有元素對

在給定的陣列中找出兩個元素和為給定值的所有元素對

Design an algorithm to find all pairs of integers within an array which sum to

a specified value. 

使用hash map:

1假設V為給定的值,A為給定的陣列。

2建立hash map M,M將從陣列元素對映到出現次數。

3對陣列中的元素A[i]:

如果 V-A[i] 在M中,列印A[I] 和V-A[I], M[V-A[i]] 次.

如果A[i]在M中,增加M[A[i]],否則M[A[i]] = 1.

演算法能處理例如兩個元素相等以及重複元素的特殊例子。 (V/2, V/2) (e.g. V=7 and A=[3,4,3,4]).

SOLUTION
One easy and (time) efficient solution involves a hash map from integers to integers. This
algorithm works as follows:
1. Let be V be the specified value, and let A be the array.
2. Create a hash map, M, which will map from array elements to occurrence counts.
3. For each element A[i] in the array:
If V-A[i] is present in M, then print A[I] and V-A[I], M[V-A[i]] times.
If A[i] is present in M, increment M[A[i]], otherwise let M[A[i]] = 1.
This algorithm conveys the special cases such as identical pairs (V/2, V/2) and repeated values

(e.g. V=7 and A=[3,4,3,4]).

另外一種解法:

補充的定義:如果要找出和為z的兩個元素,x的補充就為z-x。

演算法:假設陣列已經是排好序的。讓first指向陣列頭,last指向陣列尾。如果 first + last < sum,表示first沒有補充,first前移。如果 first + last > sum,last後移。如果 first + last == sum first++  last--. 當first比last大時停止移動。

Alternate Solution
Definition of Complement: If we’re trying to find a pair of numbers that sums to z, the complement
of x will be z - x (that is, the number that can be added to x to make z). For example,
if we’re trying to find a pair of numbers that sum to 12, the complement of –5 would be 17.
The Algorithm: Imagine we have the following sorted array: {-2 -1 0 3 5 6 7 9 13 14 }. Let first
point to the head of the array and last point to the end of the array. To find the complement
of first, we just move last backwards until we find it. If first + last < sum, then there is no complement
for first. We can therefore move first forward. We stop when first is greater than last.
Why must this find all complements for first? Because the array is sorted and we’re trying progressively
smaller numbers. When the sum of first and last is less than the sum, we know that
trying even smaller numbers (as last) won’t help us find a complement.
Why must this find all complements for last? Because all pairs must be made up of a first and

a last. We’ve found all complements for first, therefore we’ve found all complements of last.

//Implementation:
#include <iostream>
#include <conio.h>
#include <algorithm>
using namespace std;
void print_pairs(int * ptr, int num, int sum) {
	std::sort(ptr, ptr + num);
	int first = 0;
	int last = num - 1;
	while (first < last) {
		int s = ptr[first] + ptr[last];
		if (s == sum) {
			cout << ptr[first] << “ “ << ptr[last] << endl;
			++first;
			--last;
		} else {
			if (s < sum) {
				++first;
			} else {
				--last;
			}
		}
	}
}

相關推薦

給定陣列元素給定所有元素

Design an algorithm to find all pairs of integers within an array which sum to a specified value.  使用hash map: 1假設V為給定的值,A為給定的陣列。 2建立has

陣列元素等於指定數值,並輸出位置。

從陣列中找出和為指定值的第一對元素 1、這博文主要是實現了從陣列中找到兩個元素之和與指定值相等的元素,並輸出這兩個元素的陣列下標。 2、若有多對元素之和等於指定元素,那麼只需找到第一對並輸出結果即可。 程式思想及分析 1、通過快速排序對陣列進行排序,

1.無序陣列個數使其等於給定

碰到這種類似題目可以根據條件不同寫出不同時間複雜度的程式碼: 1.最暴力的遍歷,時間複雜度為O(n^2) 2.一般情況下先排序,再從兩邊向中間搜尋結果,時間複雜度為O(nlogn + n) int i = 0, j = numbers.size() - 1; while

給定陣列最大的個數——二分遞迴

分析1:對於給定陣列找出其中最大的兩個數,很容易想到的就是遍歷陣列。首先遍歷整個陣列,找出最大的一個元素並記錄下該位置;然後分別遍歷該位置之前的區間和該位置之後的區間,分別找出這兩個子區間的最大值,然

陣列數字的等於指定數字(4Sum)

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in

陣列第二大的數 基本方法 若還有其他方法不要小氣希望能貼在下面

//不知有什麼方法可以不用求最大的數就能把第二大的數找出來  若大牛知道  希望賜教  謝謝         int i,j;         int a[10]={0,9,23,7,6,5,12,3,2,1};         int tm,tn;         tm

演算法32--求給定陣列某一段連續區間之和的起始索引

給定一個數組以及一個目標數,求陣列中一段連續的區間使得該區間元素之和為目標數。 例如num=[1,2,3,4,5] target=10  結果返回[0,3] 解法一:遍歷所有情況  時間複雜度N2 def getSumIndex2(num=[1,2,3,4,5,6,7

演算法--求給定陣列某一段連續區間之和的起始索引

給定一個數組以及一個目標數,求陣列中一段連續的區間使得該區間元素之和為目標數。 例如num=[1,2,3,4,5] target=10  結果返回[0,3] 解法一:遍歷所有情況  時間複雜度N2 def getSumIndex2(num=[1,2,3,4,5,6,7,

遞迴分治問題之有序序列的中間

問題描述:         You are interested in analyzing some hard-to-obtain data from two separate databases. Each database contains n numerical va

(pyhon)給定一個整數陣列 nums 一個目標值 target,請你在該陣列目標值的那 整數,並返回他們的陣列下標。

方法一:使用最容易理解的遍歷陣列進行查詢 def solution(nums,target): #如果列表長度小於2,則直接結束 if len(nums) < 2: return #兩次迴圈列表,分別對列表中的所有可能的數字進行相加

js陣列不同的元素

function arr(array,array2){     var arr3 = [];      for(鍵入陣列){           var stra = arra

一個整數陣列,有元素只出現一次,其他所有元素均出現次。 只出現一次的那元素。(java實現)

一個整數陣列中,有兩個元素只出現一次,其他所有元素均出現兩次。 找出只出現一次的那兩個元素。 思路大概是這樣的:因為除了這兩個只出現一次的數字外,其餘都是成對出現的,有一種運算子,異或運算,兩個相同的數字異或之後為0,所以將陣列中所有的數字依次異或,結果就是這個兩個支出現一

陣列相同的元素,不排序直接次迴圈取出

import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Test{ /** * 獲取兩個整型陣列之間的重複元素集合 * @param a

時間殺手—for迴圈—如何list的相同元素

import numpy import datetime a = numpy.random.randint( 5,1000,100000 ) b = numpy.random startt1 = datetime.datetime.now() l11 = sorted(list(set(a)))

【死磕演算法之1刷Leetcode】——有序陣列位數【Median of Two Sorted Arrays】O(log(m+n))

Median of Two Sorted Arrays 題目難度:hard 題目要求: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two s

LeetCode千題斬之有序陣列位數

題目:There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run ti

隨筆-字串不相同的元素

題目: 給定兩個字串 s 和 t,它們只包含小寫字母。 字串 t 由字串 s 隨機重排,然後在隨機位置新增一個字母。 請找出在 t 中被新增的字母。 示例: 輸入: s = “abcd” t = “abcde” 輸出: e 解釋: ‘e’ 是那個被新增的字母。

陣列一對元素,其是一個給定的目標數字。假設陣列只存在一個符合要求的數值,返回這些數值的下標

【解題分析】對於陣列中某個下標i,如何判斷它是否屬於符合條件的兩個數字之一?最直觀的就是再次掃描數字,判斷target-array【i】是否存在於陣列中。這樣做時間複雜度O(n^2),效率不高,原因是沒有儲存之前的處理結果,每次都在做重複的工作。儘管效率不高,但

R-數列的相同元素

R-找出兩列數中的相同數 通常在用交叉判斷,比如滿足A條件的點以及同時滿足B條件的點 a <- c(1,3,5,7,9) b <- c(3,6,8,9,10) c <- c(2,3,4,5,7,9) 要找出a,b,c中的相同數字 解決辦法一: inte

給定一個n整數的陣列S,是否存在S的4個數,使得a + b + c + d = target。 在陣列所有唯一的四元組,給目標的總和。

本題源自LeetCode ------------------------------------------ 思路1 :回溯法 超時 程式碼; vector<vector<int> > fourSum(vector<int> &