I'm practicing coding questions and i'm not sure why my code isn't working (i know it's not written very efficiently:/ )
given an array and a target number, return the indices of two numbers in the array that add up to the target number. Example: nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. (indices have to be diff)
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++)
{
if (nums[i] <= target)
{
for (int j = i; j < nums.length; j++)
{
System.out.print(nums[i]);
if (nums[i] + nums[j] == target)
{
return new int[]{i, j};
}
}
}
}
return new int[]{0,0};
}
}
Any help would be greatly appreciated!
Aucun commentaire:
Enregistrer un commentaire