Today I tried solving the below problem in leetcode:
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target.
Dictionary feature in Python is so powerful. With this Dictionary feature and List feature usage dynamically, I could write Python program very fast, even with lesser exposure in Python.
Below is my solution. Leetcode says better solution than many submissions :)
I tried writing the C solution too, which took lots of thinking. I cannot use hashtable as it eats up memory. Next solution is only to do sorting and go over each sorted elements.
Below is my solution:
Leetcode says:
- Runtime: 15 ms, faster than 89.78% of C online submissions for Two Sum.
- Memory Usage: 6.3 MB, less than 86.73% of C online submissions for Two Sum.
We can still optimize it. Please post your comments where can we optimize more. :)
Performance and memory wise , C code again proved as C is much optimized than Python: