본문 바로가기

Projects/LeetCode

LeetCode two sum brute force java

반응형

This is the first time trying to solve leetcode but, I could only code 2 repeating for statements. and never could think of from if to return statement although when I saw the answer, it was easy to understand.

 

I don't really think I understand how repeated for statement works and I will try to explain it to understand.

 

 

for(int i=0;i<nums.length;i++) { // this repeat i++


// because second for statement is contained in the first one,
// with i=0, j starts from j=0 to finish and when j finish
// i=1 starts and start j=0 again, making it possible to check all the possible cases of sum
for(int j=0;j<nums.length;j++) { 



// and because this if statement is inside the second for statement
// this returns the second for statement result.
if(target == nums[i] + nums[j]) {
return new int[] {i, j};
}

 

Exceptions and Error

There are two main errors, which are compile error and run time error.

 

Compile error means error occured during compiling.

Runtime error means error occured while executing the program.

 

When it is compile error, computer basically check the grammar and can fix the error so if we fix what the computer tells us to fix, computer would compile and run the program successfully.

 

Java classify runtime error as exception or error.

 

Error is like OutOfMemoryError, StackOverFlowError, JVM or hardware related problems, so there is noting a software engineer can do about it.

 

However, with Exception, developer can predict the exception and code it, so program doesn't end abnormally. 

 

 

So, 

 

throw new IllegalArgumentException("No two sum solution");

 

this one line of code continues the program even when it couldn't find the answer, returning No two sum solution.

 

class Solution {

	public int[] twoSum(int[] nums, int target) {
		
		for(int i=0;i<nums.length;i++) {
			for(int j=0;j<nums.length;j++) {
				if(target == nums[i] + nums[j]) {
					return new int[] {i, j};
				}
			}
		}
		throw new IllegalArgumentException("No two sum solution");
				
			}
		}
public class Test {
	public static void main(String[] args) {
		int[] nums = {6,4,3,8,7,5,2};
		Solution sol = new Solution();
		int[] result = sol.twoSum(nums, 5);
		System.out.println(result[0] + "," +result[1]);
}
}

But above code didn't get the right answer.

 

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // making list of two spaces
        int ans[] = new int[2];
        // repeating twice
        for(int i = 0; i < nums.length; i++)
        {
            int val = nums[i];
            for(int j = i + 1; j < nums.length; j++)
            {
                if(val + nums[j] == target)
                {
                    ans[0] = i;
                    ans[1] = j;
                    return ans;
                }
            }
        }
        return ans;
    }
}

 

반응형