Find nearest double in ordered ArrayList<Double> - java

I have an sorted ArrayList and I would like to find nearest element to double x in it.
double x = 50.2;
ArrayList<Double> arrayList = new ArrayList<>();
arrayList.add(12.34);
arrayList.add(86.00);
arrayList.add(87.26);
arrayList.add(241.63);
...
double findNearestDoubleInList(list, x)
{
...
}
How do I accomplish that?

Use java.lang.Math.abs to get the difference between values in the list and desired value and find the nearest one.
double answer = arrayList.get(0);
double current = Double.MAX_VALUE;
for (Double value : arrayList) {
if (Math.abs(value - x) < current) {
answer = value;
current = Math.abs(value - x);
}
}

Walk through the list and compute the absolute difference with x and the current element in the list.
Return the smallest absolute difference.
static double findNearestDoubleInList(ArrayList<Double> list, double d){
if(list.size() == 0){
return -1;
}
if(list.size() == 1){
return list.get(0);
}
double current = list.get(0);
double currentMin = Math.abs(list.get(0) - d);
for(int i = 1; i < list.size(); i ++){
double difference = Math.abs(list.get(i) - d);
if(currentMin > difference){
currentMin = difference;
current = list.get(i);
}
}
return current;
}
For algorithms like this, always assume the first element is your solution.

// Java program to find element closet to given target by binary search on the sorted array
class FindClosestNumber {
// Returns element closest to target in arr[]
public static double findClosest(double[] arr, double target)
{
int n = arr.length;
// Corner cases
if (target <= arr[0])
return arr[0];
if (target >= arr[n - 1])
return arr[n - 1];
// Doing binary search
int i = 0, j = n, mid = 0;
while (i < j) {
mid = (i + j) / 2;
// if arr[mid] and target are very close
if (Math.abs(arr[mid]-target) < 0.0001)
return arr[mid];
/* If target is less than array element,
then search in left */
if (target < arr[mid]) {
// If target is greater than previous
// to mid, return closest of two
if (mid > 0 && target > arr[mid - 1])
return getClosest(arr[mid - 1],
arr[mid], target);
/* Repeat for left half */
j = mid;
}
// If target is greater than mid
else {
if (mid < n-1 && target < arr[mid + 1])
return getClosest(arr[mid],
arr[mid + 1], target);
i = mid + 1; // update i
}
}
// Only single element left after search
return arr[mid];
}
// Method to compare which one is the more close
// We find the closest by taking the difference
// between the target and both values. It assumes
// that val2 is greater than val1 and target lies
// between these two.
public static double getClosest(double val1, double val2,
double target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
// Driver code
public static void main(String[] args)
{
double arr[] = {12.34, 86.00, 87.26, 241.63};
double target = 50.2;
System.out.println(findClosest(arr, target));
}
}

Related

perfect squares leetcode - recursive solution with memoization

Trying to solve this problem with recursion and memoization but for input 7168 I'm getting wrong answer.
public int numSquares(int n) {
Map<Integer, Integer> memo = new HashMap();
List<Integer> list = fillSquares(n, memo);
if (list == null)
return 1;
return helper(list.size()-1, list, n, memo);
}
private int helper(int index, List<Integer> list, int left, Map<Integer, Integer> memo) {
if (left == 0)
return 0;
if (left < 0 || index < 0)
return Integer.MAX_VALUE-1;
if (memo.containsKey(left)) {
return memo.get(left);
}
int d1 = 1+helper(index, list, left-list.get(index), memo);
int d2 = 1+helper(index-1, list, left-list.get(index), memo);
int d3 = helper(index-1, list, left, memo);
int d = Math.min(Math.min(d1,d2), d3);
memo.put(left, d);
return d;
}
private List<Integer> fillSquares(int n, Map<Integer, Integer> memo) {
int curr = 1;
List<Integer> list = new ArrayList();
int d = (int)Math.pow(curr, 2);
while (d < n) {
list.add(d);
memo.put(d, 1);
curr++;
d = (int)Math.pow(curr, 2);
}
if (d == n)
return null;
return list;
}
I'm calling like this:
numSquares(7168)
All test cases pass (even complex cases), but this one fails. I suspect something is wrong with my memoization but cannot pinpoint what exactly. Any help will be appreciated.
You have the memoization keyed by the value to be attained, but this does not take into account the value of index, which actually puts restrictions on which powers you can use to attain that value. That means that if (in the extreme case) index is 0, you can only reduce what is left with one square (1²), which rarely is the optimal way to form that number. So in a first instance memo.set() will register a non-optimal number of squares, which later will get updated by other recursive calls which are pending in the recursion tree.
If you add some conditional debugging code, you'll see that map.set is called for the same value of left multiple times, and with differing values. This is not good, because that means the if (memo.has(left)) block will execute for cases where that value is not guaranteed to be optimal (yet).
You could solve this by incorporating the index in your memoization key. This increases the space used for memoization, but it will work. I assume you can work this out.
But according to Lagrange's four square theorem every natural number can be written as the sum of at most four squares, so the returned value should never be 5 or more. You can shortcut the recursion when you get passed that number of terms. This reduces the benefit of using memoization.
Finally, there is a mistake in fillSquares: it should add n itself also when it is a perfect square, otherwise you'll not find solutions that should return 1.
Not sure about your bug, here is a short dynamic programming Solution:
Java
public class Solution {
public static final int numSquares(
final int n
) {
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
int j = 1;
int min = Integer.MAX_VALUE;
while (i - j * j >= 0) {
min = Math.min(min, dp[i - j * j] + 1);
++j;
}
dp[i] = min;
}
return dp[n];
}
}
C++
// Most of headers are already included;
// Can be removed;
#include <iostream>
#include <cstdint>
#include <vector>
#include <algorithm>
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
#define MAX INT_MAX
using ValueType = std::uint_fast32_t;
struct Solution {
static const int numSquares(
const int n
) {
if (n < 1) {
return 0;
}
static std::vector<ValueType> count_perfect_squares{0};
while (std::size(count_perfect_squares) <= n) {
const ValueType len = std::size(count_perfect_squares);
ValueType count_squares = MAX;
for (ValueType index = 1; index * index <= len; ++index) {
count_squares = std::min(count_squares, 1 + count_perfect_squares[len - index * index]);
}
count_perfect_squares.emplace_back(count_squares);
}
return count_perfect_squares[n];
}
};
int main() {
std::cout << std::to_string(Solution().numSquares(12) == 3) << "\n";
return 0;
}
Python
Here we can simply use lru_cache:
class Solution:
dp = [0]
#functools.lru_cache
def numSquares(self, n):
dp = self.dp
while len(dp) <= n:
dp += min(dp[-i * i] for i in range(1, int(len(dp) ** 0.5 + 1))) + 1,
return dp[n]
Here are LeetCode's official solutions with comments:
Java: DP
class Solution {
public int numSquares(int n) {
int dp[] = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
// bottom case
dp[0] = 0;
// pre-calculate the square numbers.
int max_square_index = (int) Math.sqrt(n) + 1;
int square_nums[] = new int[max_square_index];
for (int i = 1; i < max_square_index; ++i) {
square_nums[i] = i * i;
}
for (int i = 1; i <= n; ++i) {
for (int s = 1; s < max_square_index; ++s) {
if (i < square_nums[s])
break;
dp[i] = Math.min(dp[i], dp[i - square_nums[s]] + 1);
}
}
return dp[n];
}
}
Java: Greedy
class Solution {
Set<Integer> square_nums = new HashSet<Integer>();
protected boolean is_divided_by(int n, int count) {
if (count == 1) {
return square_nums.contains(n);
}
for (Integer square : square_nums) {
if (is_divided_by(n - square, count - 1)) {
return true;
}
}
return false;
}
public int numSquares(int n) {
this.square_nums.clear();
for (int i = 1; i * i <= n; ++i) {
this.square_nums.add(i * i);
}
int count = 1;
for (; count <= n; ++count) {
if (is_divided_by(n, count))
return count;
}
return count;
}
}
Java: Breadth First Search
class Solution {
public int numSquares(int n) {
ArrayList<Integer> square_nums = new ArrayList<Integer>();
for (int i = 1; i * i <= n; ++i) {
square_nums.add(i * i);
}
Set<Integer> queue = new HashSet<Integer>();
queue.add(n);
int level = 0;
while (queue.size() > 0) {
level += 1;
Set<Integer> next_queue = new HashSet<Integer>();
for (Integer remainder : queue) {
for (Integer square : square_nums) {
if (remainder.equals(square)) {
return level;
} else if (remainder < square) {
break;
} else {
next_queue.add(remainder - square);
}
}
}
queue = next_queue;
}
return level;
}
}
Java: Most efficient solution using math
Runtime: O(N ^ 0.5)
Memory: O(1)
class Solution {
protected boolean isSquare(int n) {
int sq = (int) Math.sqrt(n);
return n == sq * sq;
}
public int numSquares(int n) {
// four-square and three-square theorems.
while (n % 4 == 0)
n /= 4;
if (n % 8 == 7)
return 4;
if (this.isSquare(n))
return 1;
// enumeration to check if the number can be decomposed into sum of two squares.
for (int i = 1; i * i <= n; ++i) {
if (this.isSquare(n - i * i))
return 2;
}
// bottom case of three-square theorem.
return 3;
}
}

Finding square roots without sqrt() to .000001 precision

I'm working on making a method that will calculate the square root of a supplied integer without using Math.sqrt(). I believe everything is working except for meeting the condition of the while loop.
As of right now perfect squares will work however non perfect squares seem to loop infinitely. I'm not sure how to get it meet the conditions of the loop to break and find the square root of a non perfect square to a precision of .000001.
public static double findSquareRoot(int value)
{
value = Math.abs(value);
double mid = value / 2.0, answer = 0;
// loop until sqrt is found
while (answer * answer != value)
{
// if middle value is sqrt
if (mid * mid == value)
{
return mid;
}
// if middle value is too big to be sqrt
else if (mid * mid > value)
{
mid = mid / 2.0;
answer = mid;
}
// if middle value is too small to be sqrt
else
{
mid = (mid + value) / 2.0;
answer = mid;
}
}
return answer;
}
You need to check with given precision:
public static double findSquareRoot(int value)
{
private static final double PRECISION = 0.000001;
value = Math.abs(value);
double mid = value / 2.0, answer = 0;
// loop until sqrt is found
while (Math.abs(answer * answer - value) < PRECISION)
{
// if middle value is sqrt
if (Math.abs(mid * mid - value) < PRECISION)
{
return mid;
}
// if middle value is too big to be sqrt
else if (mid * mid > value)
{
mid = mid / 2.0;
answer = mid;
}
// if middle value is too small to be sqrt
else
{
mid = (mid + value) / 2.0;
answer = mid;
}
}
return answer;
}
This should work for non perfect square. Basically, as #Andronicus indicated, you need to check against the precision in the while condition clause.
private static double getSqrt(int x) {
final double PRECISION = 0.000001;
x = Math.abs(x);
double start = 1, end = (double )x, ans=0.0, mid = 0.0;
while (Math.abs(mid*mid - x) > PRECISION) {
//use binary search
mid = (start + end) / 2.0;
// continue to narrow the range
if (mid * mid < x) {
start = mid + 0.5;
ans = mid;
}
else {
end = mid - 0.5;
}
}
return ans;
}

How do I solve this StackOverflowError?

In this section of my MergeSort program, I am recursively dividing a unsorted array called "arr". To do this I create two subarrays, "leftArr" and "rightArr", then I fill "leftArr" and "rightArr" with the first half of "arr" and the second half of "arr" respectively. Afterwards I will use recursion to divde / sort leftArr and rightArr.
Just wanted clarify: mid = arr.length;
To initialise the rightArr I do the following:
double halfLength = arr.length * 0.5;
if((!(halfLength < 0)) && (!(0 < halfLength))){
// if right array is an even num, length of right array is mid
rightArr = new int [mid];
} else
{
// else right arrays length is mid + 1
rightArr = new int[mid + 1];
}
When I do this I get no errors:
if(arr.length % 2 == 0){
// if right array is an even num, length of right array is mid
rightArr = new int [mid];
} else
{
// else right arrays length is mid + 1
rightArr = new int[mid + 1];
}
But my project doesn't allow me to use the modulus operator "%" and the "==" operator.
Im not getting any syntax error. All i see in the console window is:
" Exception in thread "main" java.lang.StackOverflowError ".
The Complete recursive method looks like this:
public int[] mergeSort(int[] arr) {
if (arr.length < 2){
return arr; // if array has only one element, its already sorted
}
int mid = arr.length / 2; // find midpoint of array
int leftArr[] = new int [mid]; // create left subarray of length mid
int rightArr[]; // create right subarray
/* if(arr.length % 2 == 0){
// if right array is an even num, length of right array is mid
rightArr = new int [mid];
} else
{
// else right arrays length is mid + 1
rightArr = new int[mid + 1];
}*/
double halfLength = arr.length * 0.5;
if((!(halfLength < 0)) && (!(0 < halfLength))){
// if right array is an even num, length of right array is mid
rightArr = new int [mid];
} else
{
// else right arrays length is mid + 1
rightArr = new int[mid + 1];
}
// create a resultArr of size arr, to store the sorted array
int resultArr[] = new int [arr.length];
int i = 0;
// Copy first half of arr[] into leftArr[]
while(i < mid){
leftArr[i] = arr[i];
i = i + 1;
}
int j = mid;
int indexOfRight = 0;
// Copy second half of arr into rightArr
while(j < arr.length){
rightArr[indexOfRight] = arr[j];
indexOfRight = indexOfRight + 1;
j = j + 1;
}
// Recursively call mergeSort to sort leftArr and rightArr
leftArr = mergeSort(leftArr);
rightArr = mergeSort(rightArr);
// merge leftArr and rightArr into a resultant Array, and then return the resultArr
return resultArr = merge(leftArr, rightArr);
}
This is how I merge:
public int[] merge(int[] a1, int[] a2) {
// TO BE COMPLETED
int lengthOfRes = a1.length + a2.length;
int resArr[] = new int [lengthOfRes]; // create resultant array of size a1 + a2
int a1Index = 0;
int a2Index = 0;
int resIndex = 0;
while((a1Index < a1.length) || (a2Index < a2.length))
{
if((a1Index < a1.length) && (a2Index < a2.length)){
// if a1's element is <= a2's element, then insert a1's elem in resArr
if(a1[a1Index] < a2[a2Index]){
resArr[resIndex] = a1[a1Index];
a1Index = a1Index + 1;
resIndex = resIndex + 1;
} else
// else, insert a2's elem in resArr
{
resArr[resIndex] = a2[a2Index];
a2Index = a2Index + 1;
resIndex = resIndex + 1;
}
}
// Here, if there are any of a1's elements left over, then insert them into resArr
else if(a1Index < a1.length){
resArr[resIndex] = a1[a1Index];
a1Index = a1Index + 1;
resIndex = resIndex + 1;
}
// Here, if there are any of a2's elements left over, then insert them into resArr
else
{
resArr[resIndex] = a2[a2Index];
a2Index = a2Index + 1;
resIndex = resIndex + 1;
}
}
return resArr; // return the resulting array
}
How can I fix this problem?
Thanks in advance!
This algorithm is not sorting anything. You are only breaking the array recursively, but there isn't any comparison.
This site have a good explanation about merge sorting algorithm: http://algs4.cs.princeton.edu/22mergesort/
http://algs4.cs.princeton.edu/22mergesort/Merge.java.html
It's worth studying it.
The problem is that this code
double halfLength = arr.length * 0.5;
if((!(halfLength < 0)) && (!(0 < halfLength)))
do not determine if the arr.length is even. Try this:
public boolean isEven(int number) {
// return (number - (number / 2) * 2) == 0;
return (!((number - (number / 2) * 2) > 0)) && (!((number - (number / 2) * 2) < 0));
}
Here is another method without division, mod or equals operations
public boolean isEven(int number) {
number = number < 0 ? number * -1 : number;
if (number < 1) {
return true;
}
if (number > 0 && number < 2) {
return false;
}
return isEven(number - 2);
}

How can i fin the index using exponential, binary or interpolatin search recursively? [duplicate]

This question already has an answer here:
How can I locate an index given the following constraints? [closed]
(1 answer)
Closed 9 years ago.
Given an array of n integers A[0…n−1], such that ∀i,0≤i≤n, we have that |A[i]−A[i+1]|≤1, and if A[0]=x, A[n−1]=y, we have that x<y. Locate the index j such that A[j]=z, for a given value of z, x≤ z ≤y
I dont understand the problem. I've been stuck on it for 4 days. Any idea of how to approach it with binary search, exponential search or interpolation search recursively? We are given an element z find the index j such that a [j] = z (a j) am i right?.
static int binarySearch(int[] searchArray, int x) {
int start, end, midPt;
start = 0;
end = searchArray.length - 1;
while (start <= end) {
midPt = (start + end) / 2;
if (searchArray[midPt] == x) {
return midPt;
} else if (searchArray[midPt] < x) {
start = midPt + 1;
} else {
end = midPt - 1;
}
}
return -1;
}
You can use the basic binary search algorithm. The fact that A[i] and A[i+1] differ by at most 1 guarantees you will find a match.
Pseudocode:
search(A, z):
start := 0
end := A.length - 1
while start < end:
x = A[start]
y = A[end]
mid := (start+end)/2
if x <= z <= A[mid]:
end := mid
else if A[mid] < z <= y
start := mid + 1
return start
Note that this doesn't necessarily return the first match, but that wasn't required.
to apply your algorithms your need a sorted array.
the condition of you problem says that you have an array which has elements that differ with max 1, not necessarily sorted!!!
so, here are the steps to write the code :
check if problem data respects given conditions
sort input array + saving old indexes values, so later can can initial positions of elements
implement you search methods in recursive way
Binary search source
Interpolation search source
Here's full example source :
public class Test {
// given start ======================================================
public int[] A = new int[] { 1, 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6,
7, 8 };
public int z = 4;
// given end =======================================================
public int[] indexes = new int[A.length];
public static void main(String[] args) throws Exception {
Test test = new Test();
if (test.z < test.A[0] || test.z > test.A[test.A.length - 1]){
System.out.println("Value z="+test.z+" can't be within given array");
return;
}
sort(test.A, test.indexes);
int index = binSearch(test.A, 0, test.A.length, test.z);
if (index > -1) {
System.out.println("Binary search result index =\t"
+ test.indexes[index]);
}
index = interpolationSearch(test.A, test.z, 0, test.A.length-1);
if (index > -1) {
System.out.println("Binary search result index =\t"
+ test.indexes[index]);
}
}
public static void sort(int[] a, int[] b) {
for (int i = 0; i < a.length; i++)
b[i] = i;
boolean notSorted = true;
while (notSorted) {
notSorted = false;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
int aux = a[i];
a[i] = a[i + 1];
a[i + 1] = aux;
aux = b[i];
b[i] = b[i + 1];
b[i + 1] = aux;
notSorted = true;
}
}
}
}
public static int binSearch(int[] a, int imin, int imax, int key) {
// test if array is empty
if (imax < imin)
// set is empty, so return value showing not found
return -1;
else {
// calculate midpoint to cut set in half
int imid = (imin + imax) / 2;
// three-way comparison
if (a[imid] > key)
// key is in lower subset
return binSearch(a, imin, imid - 1, key);
else if (a[imid] < key)
// key is in upper subset
return binSearch(a, imid + 1, imax, key);
else
// key has been found
return imid;
}
}
public static int interpolationSearch(int[] sortedArray, int toFind, int low,
int high) {
if (sortedArray[low] == toFind)
return low;
// Returns index of toFind in sortedArray, or -1 if not found
int mid;
if (sortedArray[low] <= toFind && sortedArray[high] >= toFind) {
mid = low + ((toFind - sortedArray[low]) * (high - low))
/ (sortedArray[high] - sortedArray[low]); // out of range is
// possible here
if (sortedArray[mid] < toFind)
low = mid + 1;
else if (sortedArray[mid] > toFind)
// Repetition of the comparison code is forced by syntax
// limitations.
high = mid - 1;
else
return mid;
return interpolationSearch(sortedArray, toFind, low, high);
} else {
return -1;
}
}
}

A recursive algorithm to find two integers in an array that sums to a given integer

I need an algorithm to determine if an array contains two elements that sum to a given integer.
The array is sorted.
The algorithm should be recursive and runs in O(n).
The recursive step should be based on the sum, meaning the method passes the sum and return true or false depending on the end result (if two elements are found - return true, else - return false)
Only linear data structures can be used.
Any ideas are appreciated..
You can convert any iterative algorithm into a recursive one by using (for instance) tail recursion. I'd be more expansive, if it weren't homework. I think you'll understand it from the other post.
Normally I'd use a Map, but since one of the requirements is to use a linear data structure, I think that's excluded, so I'd go about using a boolean array.
public boolean hasSum( int[] numbers, int target )
{
boolean[] hits = new boolean[ target + 1 ];
return hasSumRecursive( 0, numbers, target, hits );
}
public boolean hasSumRecursive( int index, int[] numbers, int target, boolean[] hits )
{
...
}
Hopefully this is a good enough hint.
I think hash is ok, for example, 1,3,7,9,12,14,33...
if we want sum=21, we hash the numbers into a hash table, So, O(n).
we iterator them, when we get 7, we let 21-7=14, so we hash 14, we can find it. so 7+14=21,
we got it!
Here is a solution witch takes into account duplicate entries. It is written in javascript and assumes array is sorted. The solution runs in O(n) time and does not use any extra memory aside from variable.
var count_pairs = function(_arr,x) {
if(!x) x = 0;
var pairs = 0;
var i = 0;
var k = _arr.length-1;
if((k+1)<2) return pairs;
var halfX = x/2;
while(i<k) {
var curK = _arr[k];
var curI = _arr[i];
var pairsThisLoop = 0;
if(curK+curI==x) {
// if midpoint and equal find combinations
if(curK==curI) {
var comb = 1;
while(--k>=i) pairs+=(comb++);
break;
}
// count pair and k duplicates
pairsThisLoop++;
while(_arr[--k]==curK) pairsThisLoop++;
// add k side pairs to running total for every i side pair found
pairs+=pairsThisLoop;
while(_arr[++i]==curI) pairs+=pairsThisLoop;
} else {
// if we are at a mid point
if(curK==curI) break;
var distK = Math.abs(halfX-curK);
var distI = Math.abs(halfX-curI);
if(distI > distK) while(_arr[++i]==curI);
else while(_arr[--k]==curK);
}
}
return pairs;
}
I solved this during an interview for a large corporation. They took it but not me.
So here it is for everyone.
Start at both side of the array and slowly work your way inwards making sure to count duplicates if they exist.
It only counts pairs but can be reworked to
use recursion
find the pairs
find pairs < x
find pairs > x
Enjoy!
It is pretty easy. It is important for array to be sorted.
Correct algorithm with O(n) time complexity and no additional space is:
public static boolean isContainsSum(int[] arr, int sum) {
for (int i = 0, j = arr.length - 1; i < j; ) {
if (arr[i] + arr[j] == sum)
return true;
if (arr[i] + arr[j] < sum)
i++;
else
j--;
}
return false;
}
To make it recursive, you need just replace i and j iterations with recursive call:
public static boolean isContainsSumRecursive(int[] arr, int sum) {
return isContainsSumRecursive(arr, sum, 0, arr.length - 1);
}
private static boolean isContainsSumRecursive(int[] arr, int sum, int i, int j) {
if (i == j)
return false;
if (arr[i] + arr[j] == sum)
return true;
if (arr[i] + arr[j] < sum)
return isContainsSumRecursive(arr, sum, i + 1, j);
return isContainsSumRecursive(arr, sum, i, j - 1);
}
Here is my solution: I iterate until the first number is greater than the expected sum, then until to second one or the sum of two is greater than the expected sum. If I do not want a correct answer, I return {-1,-1} (assuming all numbers are positive integers)
{
private static int[] sumOfTwo(int[] input, int k) {
for (int i = 0; i < input.length - 1; i++) {
int first = input[i];
for (int j = 1; j < input.length; j++) {
int second = input[j];
int sum = first + second;
if (sum == k) {
int[] result = {first, second};
return result;
}
if (second > k || sum > k) {
break;
}
}
if (first > k) {
break;
}
}
int[] begin = {-1, -1};
return begin;
}
}
Here is the recursion method to perform the groupSum
public boolean groupSum(int start, int[] nums, int target)
{
if (start >= nums.length) {
return (target == 0);
}
return groupSum(start + 1, nums, target - nums[start]) || groupSum(start +
1,nums,target)
}
def ExistsSum(A, i, j, Target):
if i >= j:
return False # Failure, all candidate pairs exhausted
if A[i] + A[j] < Target:
return ExistsSum(A, i+1, j, Target) # Try a larger sum
if A[i] + A[j] > Target:
return ExistsSum(A, i, j-1, Target) # Try a smaller sum
return True # Success
Run with
ExistsSum(A, 0, len(A)-1, Target)
bool solve(vector<int> &sorted_array, int l, int r, int target) {
if(l>=r) {
return false;
}
if(sorted_array[l] + sorted_array[r] == target) {
return true;
}
if(sorted_array[l] + sorted_array[r] > target) {
return solve(sorted_array, l, r-1, target);
}
if(sorted_array[l] + sorted_array[r] < target) {
return solve(sorted_array, l+1, r, target);
}
}
int main() {
vector<int> a = ...
solve(a, 0, a.size() - 1, target)
}
Here is my solution using recursion
pair<int,int> twoSum(int arr[], int s, int e, int target, pair<int, int>p){
//base case
if(arr[s] + arr[e] == target){
// pair<int,int>p;
p.first = arr[s];
p.second = arr[e];
return p;
}
while(s < e-1){
if(arr[s] + arr[e] < target){
s++;
return twoSum(arr, s, e, target, p);
}
if(arr[s] + arr[e] > target){
e--;
return twoSum(arr, s, e, target, p);
}
}
//if there is no pair possible
cout<<"pair is not possible" <<endl;
return p;
}
Sort the array. Search for the complement of each number (sum-number). Complexity O(nlogn).

Categories