A summary of Lintcode greedy law problem

Source: Internet
Author: User
Tags arrays lintcode stringbuffer

Greedy method of the subject of the main test you will not do, know know, do not know that it is difficult to know. There is no routine, so you need to pass these questions over.

A. Single number

In an array, each number appears 2 times, and only one number appears 1 times, asking for the number to be found. It can be recorded with HashSet, but it consumes extra space, and HashSet's search takes extra time. Can take advantage of XOR operation ^,a^a=0, A^0=a, according to the Exchange law a^b=b^a, such as 3^4^3=4, according to the nature of XOR or operation, we can make all the elements in turn different or operation, the same element is different or 0, the final remaining element is a single number. Time complexity O (n), Spatial complexity O (1).

    public int singlenumber (int[] A) {
        int res = 0;
        for (int i = 0; i < a.length; i++) {
            res ^= a[i];
        }
        return res;
    }


. Single number II

The title says that, in addition to a number, the others appear 3 times, asking for a number that only appears 1 times.

The intuitive approach is to use HashMap to count occurrences and then output the number of occurrences of 1, but this method consumes extra space. Is there any way to do it in the place? That's the bit arithmetic.

The title has been said, except for a number, the others have appeared 3 times. If we remove that particular number, for each and sum of the remaining numbers in the 0 to 31 digits, each of the 1 occurrences will necessarily be a multiple of 3. So, the solution is here to break each digit down to 32 bits, counting the number of 1 occurrences on each bit. Finally, for each bit on the number of 1 appear to 3 modulo, the result of the modulo is to find the number.

    public int singlenumberii (int[] A) {
        int[] bit = new INT[32];
        int res = 0;
        for (int i = 0, I < i++) {for
            (int j = 0; J < A.length; J + +) {
                if (((A[j] >> i) & 1) = = 1) { c6/>bit[i]++;
                }
            }
            Res + = ((Bit[i]% 3) << i);
        }
        return res;
    }

A. Single number III

This question is a variant of the above single number. In addition to the number B and the number C, each of the remaining numbers appears 2 times in array A.

And the last single number is only one digit did not appear 2 times, so the problem can be directly from beginning to end, or, to get the answer. But how does this problem be done with a single number solution?

This question has two unknowns B and C, directly do XOR or certainly not, then how to break the problem by some transformations, so that can be applied to the solution of single number to do, is the topic interesting place.

If the problem is first applied directly to the method of single number, the result is the XOR of B and C: B^c. How to extract B and C from the b^c?

From a microscopic point of view, we see B and C from the 32-bit integer perspective. Because B and C are definitely different, so b^c must have a 1, as shown below:


So when we find this k, we can follow the K bit is equal to 1, the original array A is divided into two sub-arrays, and these two sub-arrays contain B and C respectively, then the only need to apply the single number of the algorithm directly to the two sub-arrays, you can get B and C.

    Public list<integer> SINGLENUMBERIII (int[] a) {
        int res = 0, a = 0, b = 0;
        list<integer> result = new ArrayList ();
        
        for (int i = 0; i < a.length; i++) {
            res ^= a[i];
        }
        
        int flag = 1;
        while (flag & res) = = 0) {
            flag <<= 1;
        }
        
        for (int i = 0; i < a.length; i++) {
            if ((flag & a[i) = = 0) {
                A ^= a[i];
            } else {
                b ^= a[i];
  }
        }
        Result.add (a);
        Result.add (b);
        
        return result;
    }


Majority number

In an array, there is a number that appears more than half the length of the array, which is required to find the number. At first, I must have thought of doing it with HashMap, counting the number of occurrences, but the problem requires no extra space. Can only be done by greedy method.

A simple method is to sort the array, and then the element labeled N/2 is the value to return, because notice that the topic says there must be more than half the number of occurrences of an element, then the ordered element will certainly appear in the middle (provable), the time complexity is the sorting complexity O (NLOGN)

There are, of course, better linear algorithms: each time you find a pair of different elements from the array, delete them from the array until you iterate through the entire set of numbers. Since this problem already indicates that there must be an element with more than half occurrences, there must be at least one element in the array after iterating through the array. Moore voting algorithm--each find two different element, it is the right to delete the count--, the final remaining must be asked. Time complexity: O (N)

    public int Majoritynumber (arraylist<integer> nums) {
        int count = 0;
        int candidate = 0;
        for (int i = 0; i < nums.size (); i++) {
            if (count = = 0) {
                count = 1;
                candidate = Nums.get (i);
            } else {
                if (candidate = = Nums.get (i)) {
                    count++;
                } else {
                    count--;
        }}} return candidate;
    }
For details and animated demonstrations of the Moore voting algorithm, you can refer to UT Austin University's This: http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html


Majority number II

Similar to the previous question, but to find out that the number of occurrences in the array exceeds One-third. By enumerating, we can find that the number of more than One-third in the array has a maximum of 2, we can use the Moore voting law to find these 2 numbers, and then compare them who appear more times, return that more number, can refer to the blog: http://www.cnblogs.com/ Grandyang/p/4606822.html and Http://www.cnblogs.com/yuzhangcmu/p/4175779.html

    public int Majoritynumber (arraylist<integer> nums) {
        int candidate1 = 0, Candidate2 = 0, count1 = 0, count2 = 0;
        ///Find 2 candidates for
        (int num:nums) {
            if (num = = candidate1) {
                count1++;
            } else if (num = = Candidate2) { c7/>count2++;
            } else if (count1 = = 0) {
                candidate1 = num;
                count1++;
            } else if (Count2 = = 0) {
                candidate2 = num;
                count2++;
            } else {
                count1--;
                count2--;
            }
        }
        
        To vote for these 2 candidates, find the larger that number
        count1 = Count2 = 0;
        for (int num:nums) {
            if (num = = candidate1) {
                count1++;
            } else if (num = = candidate2) {
                Count2++;
  }
        }
        //Returns the majority of the two
        count1 > count2? candidate1:candidate2;
    }

182. Delete Digits

In an array, delete the number of K so that the remaining number is the smallest integer.

First, take a simple input example, such as the input string a= "859", k=1, so we're going to delete a character here. Obviously deleting the character 8 here will give you a result. If the input string a= "859", k=2, then delete 9.

Then, we deduce the idea: because we ask for the smallest number, so we need to make the first number smaller can be, to do this, we compare two adjacent numbers, if the previous number is larger than the next number, then the previous number is deleted; If the previous number is smaller than the latter, it will not change. Continue to compare the following numbers. When the last number is reached, you do not need to compare it and delete it directly. In the above example, first compare 8 and 5, because 8:5 is big, so delete 8. If k=2, then continue to compare 5 and 9, because 5:9 is small, so do not delete; below to the last character, no more comparisons, directly delete it.

Finally, according to the above ideas, we can write the code. One thing to note here is that when the previous number in the string after processing is likely to be 0, we should skip the previous 0 and return from the first non-0 word prompt.

    public string Deletedigits (string A, int k) {
        stringbuffer sb = new StringBuffer (A);
        for (int i = 0; i < K; i++.) {for
            (int j = 0; J < Sb.length (), j + +) {
                if (j = = Sb.length ()-1 | | J + 1 < Sb.length () && Sb.charat (j) > Sb.charat (j + 1)) {
                    Sb.deletecharat (j);
                    Break
        ;
        }}} int index = 0;
        while (Sb.charat (index) = = ' 0 ') {
            index++;
        }
        Return sb.tostring (). substring (index);
    }


412. Candy

N Children stand in the same row and give them sweets. The tall child gets more sweets than the 2 children on his left and right hand side. Ask how many sweets you can spend at least to satisfy this rule.

Greedy problem, create a new array, start with the array all initialized to 1 (because if the child is all the same height, then each child can only get 1 sugar).

Then, walking from left to right, the taller, taller one takes 1 more sugars than the child on his left.

Then walk from right to left and meet higher if the higher one has less sugar than the one on his right, and the taller one takes 1 more sugars than the child on his right.

This will achieve the goal with the fewest candies:

    public int candy (int[] ratings) {
        int[] res = new Int[ratings.length];
        Initialize for
        (int i = 0; i < res.length; i++) {
            res[i] = 1;
        }
        Traverse for from left to right
        (int i = 0; i < res.length-1; i++) {
            if (ratings[i + 1] > Ratings[i]) {
                res[i + 1] = Res [i] + 1;
            }
        }
        Walk from right to left for
        (int i = res.length-1; i > 0; i--) {
            if (Ratings[i-1] > Ratings[i] && res[i-1] <= Res[i]) {
                res[i-1] = res[i] + 1;
            }
        }
        statistic
        int result = 0;
        for (int i = 0; i < res.length; i++) {
            result + = Res[i];
        }
        return result;
    }

187. Gas station

A number of gas stations were distributed on a circular road, and there was a certain amount of petrol at each station. A car drove from one gas station to another. The required oil is given in an array. There was an oil-free truck, where it was initially placed at a petrol station to allow him to walk through the entire roundabout.

We must first know that the entire ring can be completed on the premise that the total gas volume is greater than the total cost, so that there will be a starting point exists.

Suppose you start to set the starting point start = 0, and from here, if the current gas value is greater than the cost value, you can move forward.

At this point to the next site, the remaining gas plus the current gas minus cost, see if it is greater than 0, if greater than 0, then continue to move forward.

When a site is reached, if the sum value is less than 0, then any point from the starting point to the middle of the point cannot be the starting point, then the starting point is set to the next point and continue to traverse.

When the entire loop is traversed, the starting point for the current save is the request. The code is as follows:

    public int cancompletecircuit (int[] gas, int[] cost) {
        int total = 0, sum = 0, start = 0;
        for (int i = 0; i < gas.length; i++) {Total
            + = (Gas[i]-cost[i]);
            Sum + = (Gas[i]-cost[i]);
            if (Sum < 0) {
                start = i + 1;
                sum = 0;
            }
        }
        if (Total < 0) {
            return-1;
        }
        return start;
    }

196. Find the Missing number

Given a n-1 number, they range from 0 to N, asking you to find the missing number. For example: Given N = 3 and the array [0, 1, 3], return 2.

Reference to the old printing solution: http://www.geeksforgeeks.org/find-the-missing-number/After reading suddenly, the sum from 0 to N, and then subtract the sum of the array, that is the number of the missing

    public int findmissing (int[] nums) {
        int n = nums.length;
        int total = n * (n + 1)/2;
        int sum = 0;

        for (int i = 0; i < nums.length; i++) {
            sum + = Nums[i];
        }
        return total-sum;
    }



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.