Leetcode习题记录—— palindrome和数组求最大的两个数

来源:互联网 发布:周涵成都书店知乎 编辑:程序博客网 时间:2024/06/18 09:47

题目:Determine whether an integer is a palindrome. Do this without extra space.

bool isPalindrome(int x) {    int left,right;    if( x < 0)        return false;    int len = 1;    while(x / len >= 10){        len *= 10;     }    while (x > 0){        right = x % 10;        left = x / len;        if(left == right){            x = (x % len) / 10;            len = len / 100;        }        else             return false;    }    return true;}

题目要求验证整形数是否是一个回文数,回文数是指类似123321这样的数。那么这个题目难在 Do this without extra space.也就是说不能使用数组将每一位数存储再进行比较。
解决思路也很简单,逐步取出最左侧和最右侧的数并比较,然后用:x = (x % len) / 10;裁掉left right这两个数,继续进行比较。如果全部都相同那么就说明它是一个回文数。

在此再加一道题,通常我们只求数组中最大的数,现在要求同时得到最大和次大两个数,如何做呢?

int maxArea(int* height, int heightSize) {    int len = heightSize;    int first_height = height[0], second_height = height[0];    for (int i = 0; i < len ; i++){        if(first_height < height[i]){            second_height = first_height;            first_height = height[i];        }        else if (height[i] > second_height)            second_height = height[i];    }    return 0;}
原创粉丝点击