A daily algorithm problem-leetcode136-a number that only appears once

Preface

Check-in on the first day of
2019.10.26

Algorithm is the method to solve the problem. The same problem, using different algorithms, although the results obtained are the same, but the time and resources consumed are different. This requires us to learn algorithms and find out which algorithm is better.

Everyone knows that algorithms are an indispensable part of interviews with major companies. As ordinary programmers, most of us don't have much contact with algorithms in our work. If we want to work in big factories in the future and improve ourselves, we must master algorithms and data structures through deliberate practice to improve our programming ability.

Criteria for "good" algorithms

For a problem algorithm, the reason why it is called an algorithm, first of all, it must be able to solve the problem (called accuracy). Secondly, the program written by this algorithm must not crash under any circumstances (called robustness). If the accuracy and robustness are both satisfied, the next step is to consider the most important point: how efficient is the program written by the algorithm?

Operational efficiency is reflected in two aspects:

  • The running time of the algorithm. (Called "time complexity")
  • The amount of memory space required to run the algorithm. (Called "space complexity")

The standard of a good algorithm is: on the basis of meeting the requirements of the algorithm itself, the program written by the algorithm runs for a short time and occupies less memory space during the operation. This algorithm can be called a "good algorithm".

topic

One piece of leetcode 136 each day. Numbers that only appear once
Category: Array
Title link: https://leetcode-cn.com/problems/single-number/

Title description

Given an array of non-empty integers, each element appears twice except for one element. Find the element that appears only once.

Explanation:
Your algorithm should have linear time complexity. Can you do this without using extra space?

Example 1:
Input: [2,2,1]
Output: 1

Example 2:
Input: [4,1,2,1,2]
Output: 4

answer

do it yourself

  • Ideas

Use an additional HashMap to store each array element, and finally take out the one with the number 1 (seeing the topic, there is really no good idea, this method must be very inefficient)

  • Code
class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        Map<Integer, Integer> temp = new HashMap<>();

		for (int i : nums) {
    
    
			temp.put(i, temp.get(i) == null ? 1 : temp.get(i)   1);
		}
		for (int i : nums) {
    
    
			if (temp.get(i) == 1) {
    
    
				return i;
			}
		}
		return 0;
    }
}
  • Complexity analysis
  1. Time complexity: O(nn) = O(n). forThe time complexity of the loop is O(n).
  2. Space complexity: O(n). The space required by hashmap is equal to the number of elements in nums.
  • Results of the

Optimal solution: bit operation

  • Ideas
  1. Any number and 0 XOR itself: 0 ^ n => n
  2. The XOR of the same number is 0: n ^ n => 0
  3. XOR (exclusive OR) satisfies the commutative and associative laws: a ^ b ^ a = (a ^ a) ^ b = 0 ^ b = b

So we only need to XOR all the numbers to get the unique number.

  • Code
class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        int result = 0;
        for(int i : nums) {
    
    
            result^=i;
        }
        return result;
    }
}
  • Complexity analysis
  1. Time complexity: O(n). You only need to traverse the nums elements once, so the time complexity is the number of elements in nums.
  2. Space complexity: O(1).

Results of the

Concluding remarks

I suggest you do it at least twice, you may find some new techniques or methods. During the practice, you are not deliberately memorizing the answer to this question. This is not a long-term solution. Don't refer to the answer and solve the problem by yourself, so as to improve your thinking ability and programming ability.

Today is the first day of clocking in. I understand the importance of algorithms for work and development today. It takes time to pick up this part of knowledge. Maybe because it was the first time to check in, it took a full two hours today.

Friends who want to make progress together, welcome to pay attention to the author's public account: fall in love with typing code , will regularly share Java technology work, let boring technology swim!

Scan QR code to follow

[This article was first published on this site, please indicate the source for reprinting]: http://coderluo.top

Guess you like

Origin blog.csdn.net/taurus_7c/article/details/102762832