Given an
array of integers nums and an integer target, return indices of the two numbers
such that they add up to target.
You may assume that each input would
have exactly one solution, and you may not use the same element twice.
You can return the answer in any
order.
# Intuition
Solution :
like int nums[] = {1,2,3,4}
and target = 7;
select the first nums[0] and addition
nums[1], nums[2] , num[3] nums[4]
addition->
only i index
1+2 = 3
1+3 = 4
1+4 = 5
i+1 index
2+3 = 5
2+4 = 6
i+2 index
3+4 = 7
and
**one less second loop is driven**
hence condition is true
then return and non premitive in
collect the **indices**
and return new int [] {i, j}
And no match target the handle the
case
*throw new IllegalArgumentException("no match found")*
# Approach
Brute force Approach
# Complexity
- Time complexity:
O(n2)
- Space complexity:
O(1)
# Code
```
class Solution {
public int[]
twoSum(int[] nums, int target) {
for (int i
= 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (target == nums[i] + nums[j]) {
return new int[] { i, j };
}
}
}
// If no
match is found, return an empty array.
return new
int[0];
}
}
0 Comments