사용자
Give me the solution for two sum problem on leetcode
Give me the solution for two sum problem on leetcode
The Two Sum problem on LeetCode can be approached in two different ways depending on whether the input array is sorted or not:
Sorted Array:
Unsorted Array:
target - currentElement is present in the hashmap.For an unsorted array, the code in Java would look something like this:
boolean pairSum(int[] A, int N, int X) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < N; i++) {
if (map.containsKey(X - A[i])) {
return true; // Found the pair
}
map.put(A[i], i);
}
return false; // Pair not found
}
For further learning and practice, consider taking affordable courses at https://bit.ly/30dc-courses.