current position:Home>[introduction to 100 day algorithm - three questions a day - Day7] verify palindrome strings, numbers that appear only once, and most elements
[introduction to 100 day algorithm - three questions a day - Day7] verify palindrome strings, numbers that appear only once, and most elements
2021-08-25 06:44:04 【nezha】
Hello everyone , I'm Nezha , A person who loves coding Java The engineer , In line with “ More haste, less speed. , If you want to reach, you need to be quick ” The attitude of learning , Growing up on the road of no return , Growth , Just take time to polish your eyes , When I was young, I valued , When you are old, you look like a feather , When I was young, I despised , When you are old, you look like Mount Tai , The road to growth , Is also gradually put down obsession , The journey of inner peace .
Maybe , We never know where we can go , Meet who , What kind of person will you become in the end , But remember , Someone who can climb high , Never someone else's shoulder , It's the one who stays up all night , The road of life has just started , When you are tired, don't be confused , Look back , You are no longer that young and frivolous boy .
Dalian Xinghai Park
Algorithms are the foundation of advanced architects , The foundation is not solid , The earth trembled and the mountains swayed ,2021-8-14 Start to brush questions , The goal is 100 God ,300 Avenue LeetCode Algorithm problem , Sharing is the best way to learn , come on. , Hi up .
1、LeetCode 125. Verify the palindrome string
subject
Given a string , Verify that it is a palindrome string , Consider only alphabetic and numeric characters , The case of letters can be ignored .
explain : In this question , We define an empty string as a valid palindrome string .
Xiaobian vegetable solution
public static boolean isPalindrome(String s) {
// Get only numeric and alphabetic parts through regular expressions
s=s.replaceAll("[^a-zA-Z0-9]","").toLowerCase();
// Palindromes are strings that are separated in the middle , Front and back revert equally
int length = s.length();
String left = "";
String right = "";
if (length%2 != 0){
left = s.substring(0,length/2);
right = s.substring(length/2+1,length);
right = new StringBuilder(right).reverse().toString();
}else{
int mid = length/2;
left = s.substring(0,mid);
right = s.substring(mid,length);
right = new StringBuilder(right).reverse().toString();
}
return left.equals(right);
}
Although the implementation passed , But the efficiency is worrying .
Ideas and algorithms
“ Palindrome string ” It's a string that is read both forward and backward , such as “level” perhaps “noon” And so on are palindrome strings .
So why do you want to separate it in the middle , Direct reversal , Compare the reversed and initial , No, it's over ? Food .
Improved version of side dishes
public static boolean isPalindrome3(String s) {
// Get only numeric and alphabetic parts through regular expressions
s=s.replaceAll("[^a-zA-Z0-9]","").toLowerCase();
return s.equals(new StringBuilder(s).reverse().toString());
}
Efficiency is still very low , For the sake of regularity .
The boss points out the country
public static boolean isPalindrome(String s) {
StringBuilder builder = new StringBuilder();
for (int i = 0;i<s.length();i++){
char c = s.charAt(i);
if (Character.isLetterOrDigit(c)){
builder.append(Character.toLowerCase(c));
}
}
return builder.toString().equals(builder.reverse().toString());
}
The gap is still very obvious , Don't use regular expressions if you can .
2、LeetCode 136. A number that appears only once
subject
Given an array of non-empty integers , Except that an element only appears once , Each of the other elements occurs twice . Find the element that only appears once .
explain : Your algorithm should have linear time complexity . Can you do this without using extra space ?
Xiaobian vegetable solution
/**
* The brute force algorithm , Compare the current element with other elements , If there are equal , It means more than once , Unequal , It means only
*/
public static int singleNumber(int[] nums) {
for (int i = 0; i < nums.length; i++) {
boolean flag = true;
for (int j = 0; j < nums.length; j++) {
if (i != j){
if (nums[i] == nums[j]){
flag = false;
break;
}
}
}
if (flag){
return nums[i];
}
}
return 0;
}
The boss points out the country
Two values involved in the operation , If two correspond bit Same bit , The result is 0, Otherwise 1.
public static int singleNumber(int[] nums) {
int single = 0;
for (int num : nums) {
single ^= num;
}
return single;
}
3、LeetCode 169. Most elements
subject
Given a size of n Array of , Find most of them . Most elements refer to the number of occurrences in an array Greater than ⌊ n/2 ⌋ The elements of .
You can assume that the array is not empty , And there are always many elements in a given array .
Xiaobian vegetable solution
public static int majorityElement(int[] nums) {
if (nums.length == 1){
return nums[0];
}
for (int i = 0; i < nums.length; i++) {
int sum = 1;
for (int j = 0; j < nums.length; j++) {
if (i != j){
if (nums[i] == nums[j]){
sum++;
}
}
}
if (sum > nums.length/2){
return nums[i];
}
}
return 0;
}
Small cooking solution improved version
public static int majorityElement(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (!map.containsKey(nums[i])){
map.put(nums[i],1);
}else{
map.put(nums[i],map.get(nums[i]) + 1);
}
}
for (Map.Entry<Integer,Integer> entry : map.entrySet()){
if(entry.getValue() > nums.length/2){
return entry.getKey();
}
}
return 0;
}
The execution time is less than a little , Progress is remarkable , come on. .
The boss points out the country
public static int majorityElement(int[] nums) {
Arrays.sort(nums);
int mid = nums.length/2;
return nums[mid];
}
what ? You can play like this ? Think about , It's true , Because to get the mode , The mode must be greater than half , If after sorting , The middle of this array must belong to mode , frigging awesome plus.
Recommended reading
copyright notice
author[nezha],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210825064402147d.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich