zoukankan      html  css  js  c++  java
  • leetcode day1

    【所有详解可以参考】http://tianmaying.com/tutorials/tag/Leetcode?filter=hot&page=1

    Two Sum:

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    解决思路:用一个map,for循环内,遍历数组中的加数1,map用来快速查询要找的加数2,如果找到,就返回map中的这个数,否则如果map没有此数,就put进去,key是数,value是数的index

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
    
            HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
            for(int i = 0; i < numbers.length; i++){
    
                Integer diff = (Integer)(target - numbers[i]);
                if(hash.containsKey(diff)){
                    int toReturn[] = {hash.get(diff)+1, i+1};
                    return toReturn;
                }
    
                hash.put(numbers[i], i);
    
            }
    
            return null;
    
        }
    }

    Remove Duplicates from Sorted Array:

    Given input array nums = [1,1,2],

    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

    thought:

    用一个index洗刷掉数组中重复的元素,给数组重新赋值一遍,for循环遍历,当出现重复元素时,continue,否则,将下一个非重复的元素拿到前面来

    public class Solution {
        public int removeDuplicates(int[] nums) {
        if(nums.length<=1){
            return nums.length;
            
        }
        int index = 0;
        for(int i=0; i<nums.length;i++){
            if(nums[index]==nums[i]){
               continue; 
            }else{
               nums[++index]=nums[i];
            }
        }
        return index+1;
        /*Set testSet = new HashSet();
        for(int i = 0; i<nums.length ; i++){
           testSet.add(new Integer(nums[i]));
        }
        return testSet.size();*/
        }
    }
  • 相关阅读:
    Android 8.0编译过程
    Ubuntu下映射网络驱动器
    Android 指定调用已安装的某个“相机”App
    sendMessage 与 obtainMessage (sendToTarget)比较
    Linux tee命令
    Android P(9.0) userdebug版本执行adb remount失败
    adb shell get/setprop, setenforce...
    Bluedroid: 蓝牙协议栈源码剖析
    android o logcat read: unexpected EOF!
    Winform 打包 混淆 自动更新
  • 原文地址:https://www.cnblogs.com/lucky-star-star/p/4950201.html
Copyright © 2011-2022 走看看