Skip to content
This repository has been archived by the owner on Oct 14, 2021. It is now read-only.

Added TwoSum.java #543

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <iostream>
#include <cstring>
#include <vector>
#include <unordered_map>
using namespace std;

vector <string> res;
void possibleCombinations(string &digit,int index,unordered_map <int,string> &map,string &ans){
if(index == digit.length()){
res.push_back(ans);
return;
}
int current = digit[index] - '0';
string output = map[current];
for(int j=0; j<output.length(); j++){
ans.push_back(output[j]);
possibleCombinations(digit,index+1,map,ans);
ans.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits == "")
return {};
unordered_map <int,string> map;
map[2] = "abc";
map[3] = "def";
map[4] = "ghi";
map[5] = "jkl";
map[6] = "mno";
map[7] = "pqrs";
map[8] = "tuv";
map[9] = "wxyz";
string ans = "";
possibleCombinations(digits,0,map,ans);
return res;
}
int main()
{
string digits;
cout << "Type digits in range of (2,9)";
cin >> digits;
vector<string> fRes;
fRes = letterCombinations(digits);
for(auto i = fRes.begin(); i != fRes.end(); i++) {
cout<< *i << " ";
}
return 0;
}
42 changes: 42 additions & 0 deletions Programming/Java/TwoSum/twoSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Enter the array length: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter array elements (elements should be *Non-Decresing* order): ");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Enter a target sum: ");
int target = sc.nextInt();

twoSum(arr, n, target);

}

public static void twoSum(int[] arr, int n, int target) {
int left = 0, right = n - 1;
ArrayList<Integer> res = new ArrayList<Integer>(3);
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) {
res.add(left);
res.add(right);
break;
} else if (sum > target) {
right--;
} else {
left++;
}
}
for (int i = 0; i < res.size(); i++) {
int ind = res.get(i);
System.out.print(ind + 1 + " ");
}
}
}