您的位置:首页 > 编程语言 > Java开发

leetCode做题笔记二(26, 20,9)

2015-01-17 19:01 274 查看
LeetCode26:给定一个有序序列,求不同的元素个数并且返回不同序列,要求原地返回,O(1)空间(26, easy)
15分钟,第一次就AC了略开心,最好记录406ms貌似是前1%!虽然这个时间不靠谱没啥可优化的了,感觉几乎没有废代码
public int removeDuplicates(int[] A) {

int i = 1, j = 0;

for (; i < A.length; i++){
if (A[i] != A[j]) {
j++;
if (i != j)
A[j] = A[i];
}

}
return j + 1;
}

经验?:真的会有公司考这么简单?

括号匹配。(20, easy)
最好记录430ms,前10%。稍微用了点小聪明,不过不好(使用异常做判断)
经验8:使用Stack比使用数组效率高很多,对这个题而言
public boolean isValid(String s)

if (s.length() % 2 == 1)
return false;
Stack<Character> sCharacters = new Stack<>();
sCharacters.push(s.charAt(0));
for (int i = 1; i < s.length(); i++){
switch (s.charAt(i)) {
case '(':
case '{':
case '[':
sCharacters.push(s.charAt(i));
break;

case ')':
case ']':
case '}':
try {
char c = sCharacters.pop();
if (s.charAt(i) - c > 2)
return false;
} catch (Exception e) {
// TODO: handle exception
return false;
}

break;

default:
return false;
}
}
return sCharacters.isEmpty();
}

经验?:真的会有公司考这么简单?

判断一个数是不是回文数,不能用额外空间(这点好奇怪,不用额外空间连循环都没法跑了)(9, easy)(投机取巧法)
public boolean isPalindrome(int x) {
if (x < 0)
return false;
StringBuilder stringBuilder = new StringBuilder(x + "");
if (stringBuilder.reverse().toString().equals(x+""))
return true;
else
return false;
}

正规做法:少少优化。大概能跑到前50%,最好记录713ms
public boolean isPalindrome(int x) {
//negative numbers are not palindrome
if (x < 0)
return false;

// initialize how many zeros
int div = 1;
while (x / div >= 10) {
div *= 10;
}

while (x != 0) {
if (x / div != x % 10)
return false;

x = (x % div) / 10;
div /= 100;
}

return true;
}

经验?:真的会有公司考这么简单?
经验??:话说LeetCode的虚拟机性能优化过啊。我半年前跑713,现在跑了412
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息