This is the 19th day of my participation in the August More Text Challenge


Related articles

LeetCode brush questions summary: LeetCode brush questions

1. Title Description


There are duplicate elements

Given an array of integers, determine whether there are duplicate elements.

The function returns true if there is a value that appears in the array at least twice. Return false if each element in the array is different.

Start with simple questions to brush, exercise their thinking ability, for the interview preparation ~

Second, train of thought analysis


  • Look at the examples in the title, let’s clarify the idea ~

  • Example 1:

    Input: [1,2,3,1] output: trueCopy the code
  • Example 2:

    Input: [1,2,3,4] output: falseCopy the code
  • Example 3:

    Input: [1,1,1,3,3,4,3,2,4,2] output: trueCopy the code
  • Take advantage of the non-repeatable nature of sets to solve this problem.
  • Loop through all the characters until they are put into the set.
  • If the number already exists insetIn, return directlytrue. Returns if the array was successfully traversed, there are no duplicate elementsfalse.

AC code


  • The set method:

    class Solution {
        public boolean containsDuplicate(int[] nums) {
          return Arrays.stream(nums).distinct().toArray().length==nums.length?false:true;
        }
    }
    Copy the code
    • Jdk1.8 stream yyds!
  • Sorting left and right cracking method:

    class Solution { public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for (int i = 0; i < nums.length - 1; i++) { if (nums[i] == nums[i + 1]) { return true; } } return false; }}Copy the code
    • Use sort first to sort
    • As you can see, after sorting, we only need to determine whether the two adjacent values are equal!
    • If there is equality, return true.
    • Return false otherwise.

Four,

  • Thousands of ideas to solve the problem, whether this method is good, or whimsical solution, can solve is a good way! White cat black cat can catch mice cat is a good cat!
  • Here are a few other LeetCode solutions for reference!
  • Click to jump: official solution
  • Click to jump: showy solution

I see a long way to go, I’m sure I’ll keep searching ~ ** If you think I’m a good blogger! Writing is not easy, please like, follow, comment and give encouragement to the blogger ~ Hahah