aa battery
aa battery
Explore posts from servers
CC#
Created by aa battery on 11/2/2023 in #help
❔ Just got started with leetcode after a year of learning, I need some help...
So the title says it all I guess, I started with leetcode after around a year with learning and I started away with one of its problems. It took me two hours to finally get it right but my code felt so redundant and long for such a simple problem. Can I get some feedback on how to make it more efficient? Thanks So here is what I had after I was done (it was the two sum problem)
public class Solution {
public int[] TwoSum(int[] nums, int target) {
for(int i = 0; i <= nums.Length; i++) {
int e = i < nums.Length ? i + 1 : i;
var excludedNums= new int[nums.Length-e];
Array.Copy(nums, e, excludedNums, 0, excludedNums.Length);

foreach(int a in excludedNums) {
int test = nums[i] + a;
if (test == target) {
if (a == nums[i]) {
return new int[] { i, Array.IndexOf(nums, a, i+1) };
}
return new int[] { i, Array.IndexOf(nums, a) };
};
}
}
return new int[2];
}
}
public class Solution {
public int[] TwoSum(int[] nums, int target) {
for(int i = 0; i <= nums.Length; i++) {
int e = i < nums.Length ? i + 1 : i;
var excludedNums= new int[nums.Length-e];
Array.Copy(nums, e, excludedNums, 0, excludedNums.Length);

foreach(int a in excludedNums) {
int test = nums[i] + a;
if (test == target) {
if (a == nums[i]) {
return new int[] { i, Array.IndexOf(nums, a, i+1) };
}
return new int[] { i, Array.IndexOf(nums, a) };
};
}
}
return new int[2];
}
}
25 replies