Created
May 29, 2017 15:13
-
-
Save rousan/d4f4934af7b8498b4286332af3489fbf to your computer and use it in GitHub Desktop.
Solution of that two questions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
#include <cstring> | |
#include <cstdlib> | |
#include <unordered_map> | |
using namespace std; | |
void findSomePair(int* arr, int arrSize, int sum, int* pairElementIndex1, int* pairElementIndex2); | |
void testFindSomePair(); | |
void reverse(char* arr, int start, int end); | |
void reverseEachWord(char* arr); | |
void testReverseEachWord(); | |
void findSomePair(int* arr, int arrSize, int sum, int* pairElementIndex1, int* pairElementIndex2) { | |
if (arrSize <= 1) { | |
*pairElementIndex1 = -1; | |
*pairElementIndex2 = -1; | |
return; | |
} | |
unordered_map<int, int> map; | |
for (int i = 0; i < arrSize; ++i) { | |
if (map.find(arr[i]) != map.end()) { | |
*pairElementIndex1 = i; | |
*pairElementIndex2 = map[arr[i]]; | |
return; | |
} else { | |
map[sum - arr[i]] = i; | |
} | |
} | |
*pairElementIndex1 = -1; | |
*pairElementIndex2 = -1; | |
} | |
void testFindSomePair() { | |
int arr[] = {1, 4, 5, -1, 4, 7, 8, 8, 9, 12}; | |
int i1; | |
int i2; | |
findSomePair(arr, 10, 21, &i1, &i2); | |
cout << arr[i1] << " " << arr[i2] << endl; | |
} | |
void reverse(char* arr, int start, int end) { | |
char temp; | |
while (start < end) { | |
temp = arr[start]; | |
arr[start] = arr[end]; | |
arr[end] = temp; | |
start++; | |
end--; | |
} | |
} | |
void reverseEachWord(char* arr) { | |
int startInd = 0; | |
int i = 0; | |
while (true) { | |
if (arr[i] == ' ') { | |
reverse(arr, startInd, i - 1); | |
startInd = i + 1; | |
} else if (arr[i] == '\0') { | |
reverse(arr, startInd, i - 1); | |
break; | |
} | |
i++; | |
} | |
} | |
void testReverseEachWord() { | |
char str[] = "This is our country"; | |
reverseEachWord(str); | |
cout << str << endl; | |
} | |
int main() { | |
testFindSomePair(); | |
testReverseEachWord(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment