Leetcode--easy Series 9

Source: Internet
Author: User

#198 House Robber

You is a professional robber planning to rob houses along a street. Each house have a certain amount of money stashed, the only constraint stopping all from robbing each of the them are that Adjac ENT houses have security system connected and it would automatically contact the police if the adjacent houses were bro Keninto on the same night.

Given a list of non-negative integers representing the amount of money in each house, determine the maximum amount of mone Y you can rob tonight without alerting the police.

Get rid of the story background that is, an array of n elements (the value of the element is of course greater than 0), from which the elements of the m position are removed, requiring that the elements of the adjacent two positions be at most one. To obtain the maximum value of the element value

A typical DP problem. Top-down parsing problem, the maximum value f (n) of an array of n elements, can be converted to a

max{f (n-1), F (n-2) +nums[n]}

Using array A[n] to save the results of the intermediate sub-problem, the algorithm is as follows:

Note: According to the story background, there are not more than 1000 households in a street.

0msint Rob (int* nums, int numssize) {    int i=0,t1,t2;    int A[1000]={0};if (numssize==1) {a[0] = Nums[0];return a[0];} if (numssize==2) {a[1] = (nums[0]>=nums[1])? Nums[0]:nums[1];return a[1];} if (numssize==3) {if (nums[0]+nums[2]>=nums[1]) a[3] = nums[0]+nums[2];elsea[3] = Nums[1];return a[3];} if (numssize>3) {a[0] = nums[0];a[1] = (nums[0]>=nums[1])? Nums[0]:nums[1];if (Nums[0]+nums[2]>=nums[1]) a[2] = NUMS[0]+NUMS[2];ELSEA[2] = nums[1];for (i=3;i<numssize;i++) {//t1 = Rob (nums,numssize-1);//t2 = Rob (nums,numsSize-2 ) +nums[numssize-1];t1 = A[i-1];t2 = A[i-2]+nums[i];a[i] = (t1>=t2)? T1:t2;}} return a[numssize-1];}

# 202 Happy number

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process:starting with any positive integer and replace the number by the Sum of the squares of its digits, and repeat the process until the number equals 1 (where it would stay), or it loops Endl essly in a cycle which does not include 1. Those numbers for which this process ends in 1 is happy numbers.

Example: is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
Happy number refers to the sum of the squares of each digit of n and can be passed through a finite cycle and is 1

As long as there is a loop, it is not happy number

for the int type (10 bit) each bit is squared and less than: 9^2 * 10 = 810; You can save with an array, and when the value reappears, a loop appears, returning false

0msbool ishappy (int n) {int hash[810]={0};int i=1,new_n=0;if (n==1) return True;while (n!=1) {new_n = 0;while (n) {new_n + = (n%10) * (N%10); n = N/10;} n = new_n;if (n==1) return true;if (hash[n]==1) return false;elsehash[n] = 1;}}

Based on fact 1 is Happy number and 2,3,4,5,6 is not Happy number in order to change the spatial complexity to O (1), the following algorithm can be used

0msbool ishappy (int n) {    int next;    while (n > 6)    {        next = 0;        while (n)        {            Next + = (n%10) * (N%10);             n/=;        }        n = next;    }    return n = = 1;}

#203 Remove Linked List Elements

Remove all elements from a linked list of integers, that has value val.

example
given:  1---2--------6------3--4--5--6, return:  1-2- --3--4--5

<span style= "font-size:10px;" >//12ms/** * Definition for singly-linked list. * struct ListNode {*     int val; *     struct ListNode *next; *}; */struct listnode* removeelements (struct listnode* He AD, int val) {    struct ListNode *newhead,*p,*q;if (!head) return null;newhead->next = head;//simplified code, add head node  q PQ = NE whead;p = Head;while (p) {if (p->val==val) Q->next = p->next;//q invariant p moves elseq = p;//Q p Both move back p = p->next;} return newhead->next;} </span>

#204 Count Primes

Count The number of prime numbers less than a non-negative number, N .

Find the number of prime numbers between 1~n-1, note that 1 is not prime

Judge N is a The prime number method is that it cannot be divisible by numbers between 2 ~ sqrt (n). That the approximate number only has 1 and its own

The following solution is found in Leetcode discuss: both time and space complexity are close to O (n)

Https://leetcode.com/discuss/34622/my-c-solutions-in-44ms-time-nearly-o-n-and-space-nearly-o-n


44ms    /*1. Trick1 is the use square root of N.     2.  Trick2 is non-prime numbers as the Step 3. Trick3 are to use I*i as the     start.      4. Trick4 is to use count--in every loop, avoiding another traversal. */  int countprimes (int n) {    if (n <= 2) return 0;    if (n = = 3) return 1;    BOOL *prime= (bool*) malloc (sizeof (BOOL) *n);    int i=0,j=0;    int count = n-2;    int rt = sqrt (n);//trick1 for    (j = 0; J < N; j + +)    {        prime[j] = 1;    }    for (i = 2; I <= RT, i++)    {         if (Prime[i])//trick2        {for            (j=i*i; j<n; j+=i)//trick3            {                if (Prime[j])                        {                           prime[j]=0;                           Count--;//trick4}}}} free    (prime);    return count;}



Leetcode--easy Series 9

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.