staticclassSolution2{ publicint[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { returnnewint[] { i, map.get(complement) }; } } thrownew IllegalArgumentException("No two sum solution"); } }
staticclassBestSolution{ publicint[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { returnnewint[] { map.get(complement), i }; } map.put(nums[i], i); } thrownew IllegalArgumentException("No two sum solution"); } }
staticclassSolution{ publicbooleancontains(String s, char ch){ for (int i = 0; i < s.length(); i++) { if (ch == s.charAt(i)) returnfalse; } returntrue; }
publicintlengthOfLongestSubstring(String s){ if(s.equals("")) return0; int maxCount = 1; for (int i = 0; i < s.length(); i++) { int plus = 1; if ((i + plus) == s.length()) break; while (contains(s.substring(i, i + plus), s.charAt(i + plus))) { plus += 1; if (plus > maxCount) maxCount = plus; if (i + plus == s.length()) return maxCount; } } return maxCount; } }
staticclassAnswer{ publicintlengthOfLongestSubstring(String s){ Set<Character> temp = new HashSet<>(); int pt = 0, res = 0; for (int i = 0; i < s.length(); i++) { if (i != 0) temp.remove(s.charAt(i - 1)); while (pt < s.length() && !temp.contains(s.charAt(pt))) { temp.add(s.charAt(pt)); pt++; } res = Math.max(pt - i, res); } return res; } }
staticclassSolution{ publicdoublefindMedianSortedArrays(int[] nums1, int[] nums2){ if (nums1.length > nums2.length) { int[] temp = nums1; nums1 = nums2; nums2 = temp; } int m = nums1.length; int n = nums2.length;
int totalLeft = m + (n - m + 1) / 2;
int left = 0; int right = m; while (left < right) { int i = left + (right - left + 1) / 2; int j = totalLeft - i; if (nums1[i - 1] > nums2[j]) { right = i - 1; } else { left = i; } }
int i = left; int j = totalLeft - i; int nums1Left = i == 0 ? Integer.MIN_VALUE : nums1[i - 1]; int nums1Right = i == m ? Integer.MAX_VALUE : nums1[i]; int nums2Left = j == 0 ? Integer.MIN_VALUE : nums2[j - 1]; int nums2Right = j == n ? Integer.MAX_VALUE : nums2[j];