leetcode簡單題目兩道(2)

 
 

Problem

 
 

Given an integer, write a function to determine if it is a power of three.java

 
 

Follow up:

 
 

Could you do it without using any loop / recursion?node

 
 

Code:

 
 
class Solution { public: bool isPowerOfThree(int n) { if (n <= 0) return 0; int max_pow3 = log10(INT_MAX)/log10(3); int max_pow3_val = pow(3, max_pow3); return max_pow3_val % n == 0; } };
 
 

說明:

 
 

本身想了好一會,竟然沒想到對數,,汗,這個解決方法的巧在於int最大是INT_MAX,因此取log3(INT_MAX)獲得3的最大次方,而後計算出來,對n取餘便可ide

 
 

Java Code:

 
 
public class Solution { public boolean isPowerOfThree(int n) { double res = Math.log(n)/Math.log(3); return Math.abs(res - Math.rint(res))< 0.0000000001; } }
 
 

說明:

 
 

其實和上面同樣用的是對數,這就更加直接了,經過求log3(n)的結果,看與其最近的整數的差值知足幾乎爲0便可。oop

 

 

 

Problem:

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

Required:

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:

Given 1->2->3->4->5->NULL, return 1->3->5->2->4->NULL.

Note:

The relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on ...

Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }
        int count = 1;
        ListNode *p, *q, *head1, *r, *tail;
        head1 = (struct ListNode*)malloc(sizeof(struct ListNode));
        r = head1;
        p = head;
        q = p->next;
        while (p != NULL && q != NULL) {
            p->next = q->next;
            q->next = NULL;
            r->next = q;
            r = q;
            if (p->next == NULL) {
                tail = p;
            }
            p = p->next;
            if (p != NULL) {
                if (p->next == NULL) {
                    tail = p;
                }
                q = p->next;
            }
        }
        tail->next = head1->next;
        return head;
    }
};
說明:

一開始理解題目就錯了,汗,當作交換奇偶了,想法是直接交換value;
指針初始化不會了,百度才知道的,汗;
沒加tail指針,想直接用p做爲head的最後一個指針,結果死循環了;
加了tail可是在q爲NULL的時候沒賦值,奇數個的時候會執行失敗;
綜上所述,過久沒用c++了,都退化了呀。

 

實在是本身在寫代碼碰到瓶頸了,只能貼兩道作過的題目了。ui

相關文章
相關標籤/搜索