Given an array say [9, 20,-2,-45, 23, 5, 1], find the minimum po

Source: Internet
Author: User

There are two ways to solve this problem: the first is to apply the hash table to record, regardless of all negative numbers. First, we find the largest positive number in the array, for example, 23 in the array, then 23 spaces are allocated, all values are marked as 0, and then the array is traversed. If the corresponding positive number appears, it is marked as 1. In this way, after traversing the entire array, all the positive numbers that appear are recorded. Then traverse the hash table again. If the value is 0, it is the positive number we are looking. The time complexity of this method is O (n), but the space complexity changes with the change of the maximum number in the array, the space complexity is too high. So this method is not very good. The second method is to sort the array. the time complexity of fast sorting is O (nlogn), and all the negative numbers can be passed out after the blood is discharged. Set two records starting from a positive number, record the current positive number and the previous positive number of the current positive number, and then compare the two numbers. If the previous positive number + 1 is equal to the current positive number, then continue to traverse the array. If it is not equal to, the number we are looking for is the previous number + 1 of the current positive number. This is the smallest positive number we have lost. In addition, we also need to consider the special case where all values are 0 or all values are negative. It is good to return 1 directly. The time complexity of sorting is O (nlogn) plus query time O (n ). The following code details: [cpp] # include <stdio. h> int partition (int * a, int low, int high) {int x = a [low]; while (low

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.