I felt like doing an algorithm and found this problem on leetcode
Given an array of integers, find two numbers such that they add up to a specific target num
Can provide an O(n) time solution, but his memory cannot be O(1)
First you declare a key-value pair , where key is the value in the array of integers and value is the index in the array of integers. And, you need to declare a hash table to hold the key-value pairs. Then you need to iterate through the entire array of integers, if the value of this array (=sum - array[i]) is in the hash table, congratulations you found it, if not, it is stored in the hash table.
So the entire time spent is the time to insert and query the hash table. Memory is the size of the hash table.
My English is not very good, I hope I can help you.
public static void main(String args[]) {
int[] array = {150,24,79,50,88,345,3};
int sum = 200;
Map table = new HashMap<>();
StringBuilder builder = new StringBuilder();
for(int i=0;i