LeeCode
No1.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
个人LOW B代码:
public static int[] twoSum(int[] numbers, int target){
int []arr=new int[2];
for(int i=0;i<numbers.length;i++){
for(int j=numbers.length-1;j>=0;j--){
if(numbers[i]+numbers[j]==target){
arr[0]=i;
arr[1]=j;
return arr;
}
}
}
return arr;
}
较好代码:
public static int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
result[1] = i;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i);
}
return result;
}
较好代码简化版:
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; map.put(numbers[i], i))
if (map.containsKey(target - numbers[i]))
return new int[]{map.get(target - numbers[i]),i};
return new int[]{0,0};
}
}
No1 总结:个人代码,是从第一个数组元素开始查起 直到查不到,而较好代码是查询相距最近且总和为target的结果,且后者时间复杂度为O(n)==》仅限于JAVA中,C++可能是lgn, 较好代码有个bug,就是数组中有相同元素,因为map的缘故,所以排列在后面的元素会覆盖前面的元素来作为key存放到
map中,所以显示会出现同一个位置 如[3,3,2,4] 输出为1,1 No2.
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
public static int reverse(int x) {
int result=0;
while(x!=0){
int tail=x%10;//123 3
int newResult=result*10+tail;
if(result!=(newResult-tail)/10){//内存溢出处理
return 0;
}
result=newResult;
x/=10;
}
return result;
}
No3.
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
public static boolean isPalindrome(int x) {//判断整数是否是回文 121 1221 均是回文
//能被10整除不是回文,注意0%10==0;排除0的可能,且负数没有回文
if(x%10&&x!=0==0||x<0){
return false;
}
int rev=0;
while(x>rev){
rev=rev*10+x%10;
x/=10;
}
return (x==rev)||(x==(rev/10));//回文整数为偶数个或奇数个
}
No3总结: 判断整数回文 以后注意 奇偶数回文,相应的判断(return (x==rev)||(x==(rev/10));//回文整数为偶数个或奇数个)。要摒弃自己曾想用数组的方法,太LOW。
No4
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字转换成int
public int romanToInt(String s) {
int nums[]=new int[s.length()];
for(int i=0;i<s.length();i++){
switch (s.charAt(i)){
case 'M':
nums[i]=1000;
break;
case 'D':
nums[i]=500;
break;
case 'C':
nums[i]=100;
break;
case 'L':
nums[i]=50;
break;
case 'X' :
nums[i]=10;
break;
case 'V':
nums[i]=5;
break;
case 'I':
nums[i]=1;
break;
}
}
int sum=0;
for(int i=0;i<nums.length-1;i++){//先判断是否小于,因为无论>还是<都不包含 = 所以当VII这种情况,只能先判断sum-=nums[i]; 否则就会出现VII中II应该是相加而判断成相减
if(nums[i]<nums[i+1])
sum-=nums[i];
else
sum+=nums[i];
}
return sum+nums[nums.length-1];
}
方法2:
public static int romanToInt(String sst) {
int[] a = new int[26];
a['I' - 'A'] = 1;
a['V' - 'A'] = 5;
a['X' - 'A'] = 10;
a['L' - 'A'] = 50;
a['C' - 'A'] = 100;
a['D' - 'A'] = 500;
a['M' - 'A'] = 1000;
char prev = 'A';
int sum = 0;
for(char s : sst.toCharArray()) {
if(a[s - 'A'] > a[prev - 'A']) {
sum = sum - 2 * a[prev - 'A'];
}
sum = sum + a[s - 'A'];
prev = s;
}
return sum;
}
No4:VII 5+2=7 先要明白罗马数字的含义,如题很简单。
public static String longestCommonPrefix(String[] strs) {'
StringBuilder result=new StringBuilder();
if(strs!=null&&strs.length>0){//String数组引用不为空或数组有值
Arrays.sort(strs);
char[] start=strs[0].toCharArray();
char[] end=strs[strs.length-1].toCharArray();
for(int i=0;i<strs[0].length();i++){
if(end.length>i&&start[i]==end[i]){
result.append(start[i]);
}else {
return result.toString();
}
}
}
return result.toString();
}
No5总结:①Arrays.sort排序 是按字典序排列 所以可能是 abc abccccccccccccccc abcd 并不是按长度排列,所以判断的时候需要特殊注意。
②可能存在数组越界,需要判断是否为空,和末尾end数组是否比i大 ,小则比较不了
No6
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
public static boolean isValid(String s) {
Stack<Character> stack=new Stack<>();
for(char c:s.toCharArray()){
if(c=='{'){
stack.push('}');
}else if(c=='['){
stack.push(']');
}else if(c=='('){
stack.push(')');
}else if(stack.isEmpty()||stack.pop()!=c){
return false;
}
}
return stack.isEmpty();
}
No6:利用循环和Stack特性,每遍历一个 {【( 符号就push }】) 最后 再判断pop是否对应正确,最后返回isEmpty()
本解用到foreach循环, 而普通for循环和foreach循环区别(http://blog.csdn.net/mlc1218559742/article/details/52712408) 用ArrayList(数组)时普通for循环更优,而对于LinkList(List)foreach更优。本题是普通for循环更优。
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
public int strStr(String haystack, String needle) {
if(haystack.length()<needle.length()){
return -1;
}else if(needle.length()==0){
return 0;
}
if(haystack.contains(needle)){
return haystack.indexOf(needle);
}
return -1;
}
LeeCode的更多相关文章
- leecode系列--Two Sum
学习这件事在任何时间都不能停下.准备坚持刷leecode来提高自己,也会把自己的解答过程记录下来,希望能进步. Two Sum Given an array of integers, return i ...
- insertion Sort List (链表的插入排序) leecode java
逻辑简单,代码难写,基础不劳,leecode写注释不能出现中文,太麻烦,我写了大量注释,链表问题最重要的就是你那个指针式干啥的 提交地址https://oj.leetcode.com/problems ...
- 后续遍历 java leecode
以前觉得后续遍历最难写,今天看了篇博客http://blog.csdn.net/sgbfblog/article/details/7773103,其实却是我们仔细比较后续遍历和先序遍历,其实后续遍历就 ...
- 非递归实现先序遍历 java leecode 提交
写完才知道自己学习都是似是而非啊,大家可以也在leecode上提交代码,纯手写,离开eclipse第一种方式:数据结构书上的,使用栈大概思路.1.不断将根节点的左孩子的左孩子直到为空,在这个过程入栈. ...
- leecode 归并排序 链表(java)
写了好久,终于写成了.第一次zai leecode错题,题目质量很高,适合面试,与 1.归并排序是稳定的,在java中 Arrays.sort(a);中对于对象的排序就是归并排序.对于原子类型数据使用 ...
- leecode第五百五十七题(反转字符串中的单词 III)
class Solution { public: string reverseWords(string s) { string res; stack<char> sta; string:: ...
- leecode第二天-使用异或找出数组中的非重复元素
leecode题目描述如下: 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次.找出那个只出现了一次的元素. 思路: 最开始想到的是使用排序,排序之后就很容易找到非重复元素了. ...
- leecode第七十题(爬楼梯)
class Solution { public: int climbStairs(int n) { vector<unsigned long long> num;//斐波那契数列 num. ...
- leecode第四十六题(全排列)
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { int ...
- leecode第五题(最长回文子串)
class Solution { public: string longestPalindrome(string s) { int len = s.length(); || len == ) retu ...
随机推荐
- 源码解析flask的路由系统
源码解析flask的路由系统 当我们新建一个flask项目时,pycharm通常已经为项目定义了一个基本路由 @app.route('/') def hello_world(): return 'He ...
- 回收 PV - 每天5分钟玩转 Docker 容器技术(152)
当 PV 不再需要时,可通过删除 PVC 回收. 当 PVC mypvc1 被删除后,我们发现 Kubernetes 启动了一个新 Pod recycler-for-mypv1,这个 Pod 的作用就 ...
- JAVA中的Log4j
Log4j的简介: 使用异常处理机制==>异常 使用debug调试(必须掌握) System.out.Print(); 001.控制台行数有限制 002.影响性能 ...
- SpringCloud的服务注册中心(二)注册中心服务端和两个微服务应用客户端
一.构建EurekaServer工程 1.pom.xml 2.application.yml 3. EurekaServerApp.java 4.启动EurekaServer 二.构建部署 Eurek ...
- global文件中的application_start方法中做: 定时器
<%@ Application Language="C#" %> <%@ import Namespace="System.Data" %&g ...
- linux添加硬盘分区挂载教程
基本步骤:分区--格式化--挂载--写入文件 1.首先用fdisk -l命令查看添加的硬盘名称,可以看到sdb为新增的硬盘 [root@oracle ~]# fdisk -l Disk /dev/sd ...
- 菜鸟容易中的招__setattr__
class Counter: def __init__(self): self.counter = 0 # 这里会触发 __setattr__ 调用 def __setattr__(self, nam ...
- linux samba服务配置
1.下载 wget+rpm或yum install 2.配置/etc/samba/smb.conf cat smb.conf | grep setsebool 执行终端打印出来的字符串 setsebo ...
- contenteditable 插入及粘贴纯文本内容
本文主要介绍 div 标签设置 contenteditable = ' true ' 时,在光标位置插入输入的内容,或在光标位置粘贴纯文本内容.文中涉及知识,可参考以下: http://www.zh ...
- 二 Djano模型层之模型字段选项
字段选项 以下参数是全部字段类型都可用的,而且是可选的 null 如果为True,Django将在数据库中将空值存储为NULL.默认值为False 对于字符串字段,如果设置了null=True意味着& ...