diff --git a/contains-duplicate/ekgns33.java b/contains-duplicate/ekgns33.java new file mode 100644 index 000000000..2c74dbea7 --- /dev/null +++ b/contains-duplicate/ekgns33.java @@ -0,0 +1,49 @@ +import java.util.HashSet; +import java.util.Set; + +/* +start 7:06~7:14 PASS +input : integer array +output : return if input contains duplicate +constraint : +1) empty array? + nope. at least one +2) size? + [1, 10^5] +3) sorted? + nope. +4) range of elements in the array? + [-10^9, 10^9] >> max 2 * 10*9 +1 + +brute force: +ds : array. algo : just nested for-loop +iterate through the array, for index i 0 to n. n indicates the size of input + nested loop fo r index j from i+1 to n + if nums[j] == nums[i] return true; + +return false; + +time : O(n^2), space : O(1) + +better: +ds : hashset. algo : one for-loop +iterate through the array: + if set contains current value: + return true; + else + add current value to set + +return false; +time : O(n) space :O(n) + + */ +class Solution { + public boolean containsDuplicate(int[] nums) { + Set set = new HashSet<>(); + for(int num : nums) { + if(set.contains(num)) return true; + set.add(num); + } + return false; + } +} diff --git a/valid-palindrome/ekgns33.java b/valid-palindrome/ekgns33.java new file mode 100644 index 000000000..b65b10001 --- /dev/null +++ b/valid-palindrome/ekgns33.java @@ -0,0 +1,75 @@ +/* +start : 7:18 ~ +input : String s +output : return if given s is valid palindrome +constraint: +1) valid palindrome? + convert all uppercase letter to lowercase, + remove non-alphanumeric chars, + reads same forward and backward. + ex) abba, aba, a, aacbcaa +2) length of the input string + [1, 2*10^5] +3) does input string contains non-alphanumeric chars? such as whitespace + yes, but only ASCII chars + +------- + +brute force: +read each character of input string. +create a new string that only contains +lowercase letters and numbers << O(n), when n is length of string s + +create string which one is reversed. < O(n) + +compare. < O(n) + +time : O(n)-3loops, space : O(n) + +------- +better : two-pointer + +same as brute force. build new string. + +use two pointer left and right + +while left <= right + if s[left] != s[right] return false; + +return true; +------- +optimal : + +use two pointer left and right +while left <= right + if s[left] is non-alpha left++ + elif s[right] is non-alpha right-- + elif s[left] != s[right] return false + else left++ right-- + +return true +time : O(n) space : O(1) + */ +class Solution { + public boolean isPalindrome(String s) { + int left = 0; + int right = s.length() - 1; + char leftC; + char rightC; + while(left <= right) { + leftC = s.charAt(left); + rightC = s.charAt(right); + if(!Character.isLetterOrDigit(leftC)) { + left++; + } else if (!Character.isLetterOrDigit(rightC)) { + right--; + } else if (Character.toLowerCase(leftC) != Character.toLowerCase(rightC)) { + return false; + } else { + left++; + right--; + } + } + return true; + } +}