• 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();*/
        }
    }
  • 相关阅读:
    在sql中日期转化
    SQL Server标准版企业版个人版区别
    Oracle 9i默认用户
    SQL Server和Oracle的常用函数对比
    Delphi6函数大全
    Oracle 不支持 TOP 关键字
    c#连接数据库
    VC6安装及打开工程文件问题的解决
    error C4430: 缺少类型说明符 假定为 int。注意: C++ 不支持默认 int
    VC++ dll导出类
  • 原文地址:https://www.cnblogs.com/lucky-star-star/p/4950201.html
Copyright © 2020-2023  润新知