Three Sum Closest - Leet Code Solution
Problem Statement Given an array nums of n integers and an integer target, find…
September 08, 2020
Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.
Example
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
Note: You may assume the string contains only lowercase English letters.
Lets take a look at the simple solution.
public int firstUniqChar_bruteforce(String s) {
for (int i=0; i<s.length(); i++) {
boolean unique = true;
for (int j=0; j<s.length(); j++) {
if (i != j && s.charAt(i) == s.charAt(j)) {
unique = false;
break;
}
}
if (unique) {
return i;
}
}
return -1;
}
Its O(n^2)
HashMap<Character, Integer>
HashMap
1
, this is our answer1
means this character is in the string only 1 times.public int firstUniqChar(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i=0; i<s.length(); i++) {
int count = map.getOrDefault(s.charAt(i), 0);
count ++;
map.put(s.charAt(i), count);
}
for (int i=0; i<s.length(); i++) {
if (map.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
Its O(n)
Problem Statement Given an array nums of n integers and an integer target, find…
Problem Statement You are given two non-empty linked lists representing two non…
Problem Statement Given a string, determine if it is a palindrome, considering…
This is kind of preliminary technique of sorting. And, this is the first…
Problem Statement Given two strings s and t , write a function to determine if t…
Problem Statement Given an array of integers, find if the array contains any…
Introduction In this post we will see following: How to schedule a job on cron…
Introduction There are some cases, where I need another git repository while…
Introduction In this post, we will see how to fetch multiple credentials and…
Introduction I have an automation script, that I want to run on different…
Introduction I had to write a CICD system for one of our project. I had to…
Introduction Java log4j has many ways to initialize and append the desired…