LeetCode----day1

最近停下脚步,练习算法了,通过这2天的刷题,越发感觉基础知识的重要了
我会不定期发一些leetcode上我做的题目
今天把这两天学习到的写一下:

很抱歉,我第一题就卡住了,最后无奈,看了答案,写了两种方法
	
两数之和 : easy 

//	method1:  利用数组,蛮力搜索,时间复杂度 O(n^2)
    public static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length-1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] + nums[i] == target ) {
                    return new int[] { i, j };
                }
            }
        }
        return null;
   }
  //method2:Map算法,时间复杂度O(n)
    public static int[] twoSum2(int[] nums,int target) {
    	Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    	for(int i = 0 ; i != nums.length ; ++i) {
    		map.put(nums[i],i);
    	}
    	for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
			int sub = target -  entry.getKey();
    		if(map.containsKey(sub) && map.get(sub) != entry.getValue()) {
    			return new int[]{map.get(sub),entry.getValue()};
    		}
    	}
    	return null;
    }
添加两个数,   medium   这题考单项链表,不过我双向链表都会
但是知道吗,我一开始没看懂题目。。。。。。

// 添加两个参数,以一下格式输入输出
/**
 	Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
	Output: 7 -> 0 -> 8
	Explanation: 342 + 465 = 807.
	定义一个单项链表节点类,如果每次计算的节点需要进位,也就是大于 10 , 那么向后进位
 
 */
//定义链表节点
class ListNode{
//数据
	private Integer data;
	//下一个节点
    ListNode next;
	public ListNode(Integer data) {
		this.data = data;
	}
	public int value() {
		return data;
	}
}
	 public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		 ListNode current = new ListNode(0);
		 ListNode result  = current;
//		     进位
		 int carry = 0;
		 while(l1 != null || l2 != null) {
//			   每位数上之和
			 int sum = 0;
//			 判空迭代,计算和
			 if(l1 != null) {
				sum+=l1.value();
				l1 = l1.next;
			 }
			 if(l2 != null) {
				 sum+=l2.value();
				 l2 = l2.next;
			 }
//           判断进位
             if(carry > 0){
                 sum += carry;
             }
//			 判断是否进位
			carry = (sum / 10) > 0 ? (sum / 10) : 0;
//			处理sum大于10的情况
			sum = (sum >= 10) ? sum % 10 : sum;
			current.next = new ListNode(sum);
			current = current.next;
		  }
//		 最后一次如果进位大于0,就要补上
		 if(carry > 0)
			 current.next = new ListNode(carry);
//		 返回个位
		 return result.next;
	 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值