hashmap.get()==运算符返回false [英] hashmap.get() == operator returning false

查看:80
本文介绍了hashmap.get()==运算符返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决以下问题:

加里(Gary)是一个狂热的徒步旅行者.他精心跟踪自己的远足,并密切关注地形等小细节.在他的上一次远足期间,他正好走了n步.

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly n steps.

在他迈出的每一步中,他都指出这是上坡U步还是下坡D步.加里(Gary)的远足在海平面开始和结束,每次上或下的步数都代表海拔高度每变化1单位.我们定义以下术语:

For every step he took, he noted if it was an uphill, U, or a downhill, D step. Gary's hikes start and end at sea level and each step up or down represents a 1 unit change in altitude. We define the following terms:

一座山是一系列从海平面上升到从海平面上升到从海平面下降到海平面的连续步骤.

A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.

山谷是指一系列从海平面以下的连续台阶,从海平面向下的台阶开始,直至海平面的上升. 考虑到加里上次徒步旅行时上下的顺序,找到并打印出他所走过的山谷数.

A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

例如,如果加里的路径为s = [DDUUUUDD],则他首先进入2个单位深度的山谷.然后,他爬上了2个单元高的山.最后,他回到海平面并结束了远足.

For example, if Gary's path is s = [DDUUUUDD], he first enters a valley 2 units deep. Then he climbs out an up onto a mountain 2 units high. Finally, he returns to sea level and ends his hike.

功能说明

在下面的编辑器中完成countingValleys函数.它必须返回一个整数,该整数表示加里所遍历的谷数.

Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.

countingValleys具有以下参数:

countingValleys has the following parameter(s):

n:Gary采取的步骤数

n: the number of steps Gary takes

s:描述他的路径的字符串 输入格式

s: a string describing his path Input Format

第一行包含一个整数,即加里远足的步数. 第二行包含一个字符串,其中包含描述其路径的字符.

The first line contains an integer , the number of steps in Gary's hike. The second line contains a single string , of characters that describe his path.

输出格式

打印一个整数,该数字表示加里在徒步旅行中经过的山谷数.

Print a single integer that denotes the number of valleys Gary walked through during his hike.

样本输入

8 乌杜杜(UDDDUDUU)

8 UDDDUDUU

样本输出

1

以下是我在Java中的实现.它适用于小型测试用例,但不适用于大型测试用例.

Below is my implementation in java. It works for the small test cases but not for the big ones.

static int countingValleys(int n, String s) {


  //Use a hashmap to keep track of the number of moves.
  HashMap<Character,Integer> map = new HashMap();

  boolean sea = true;//check if we are at sea level

  //if both D and U have the same total no, we are at sea level.
  map.put('D',0);
  map.put('U',0);

  int valleys = 0;//count num of valleys

  for(int i = 0; i < n; i++){
      char key = s.charAt(i);

      //check if we are at sea level
      if(map.get('D') == map.get('U')){//<--PROBLEM
          sea = true;
      }
      else
          sea = false;

      if(sea == true && key == 'D'){//if we are at sea level and our next key is D, we have a valley

          valleys += 1;
      }

      map.put(key,map.get(key) + 1);//add move and update our hashmap   
  }

  return valleys;

}

问题似乎出在"if(map.get('D')== map.get('U'))",似乎对于大数返回false,有人可以告诉我为什么吗?如果我将每个map.get()分配给一个变量,然后比较这些变量,它将起作用.

The problem seems to be at "if(map.get('D') == map.get('U'))", it seems to be returning false for big numbers, can someone tell me why? It works if I assign each map.get() to a variable and compare the variables instead.

我还使用"new Object()"类型在javascript中编写了完全相同的东西,它通过了所有测试用例,但是在带有hashmap的Java中不起作用,为什么?

I also wrote the exact same thing in javascript using the "new Object()" type and it passed all the test cases, but it is not working in java with hashmap, why is that?

链接到原始问题-推荐答案

首先,如其他答案所述,在这种情况下,请使用.equals()代替==.更好的方法是,甚至不需要使用Map.一个整数就足够了.

First, as mentioned in other answer, use .equals() instead of == in this case. An even better approach is, you don't even need to use a Map. Just one integer will be good enough.

您的问题是...returning false for big numbers, can someone tell me why?

这是原因.

您需要了解几件事

首先,您需要知道Java中有两种类型的变量:基本变量和参考变量.

First, you need to know there are two types of variable in Java: Primitive and Reference.

整数通常是基元,因此变量本身就是整数值:int a = 1234;:a本身的值为1234.

An integer is usually a Primitive, so the variable itself is the integer value: int a = 1234; : a itself is having value 1234.

要比较原始变量,应使用==

To compare primitive variable, you should use ==

对于引用类型,变量本身是指针".在Java中,有用于原语的Wrapper类.例如,Integerint的包装.因此,在Integer a = new Integer(1234);中,a不包含1234的值.它是指向Integer对象引用的指针.在引用类型变量上使用==不会比较内容,而只是检查指针值是否相同(即检查指针是否指向相同的对象实例)

For reference type, variable itself is a "pointer". In Java there are Wrapper Classes for primitives. For example, Integer is the wrapper for int. So in Integer a = new Integer(1234);, a is not containing value of 1234. It is a pointer pointing to an Integer object reference. Using == on reference type variables does not compare the content, but only check if the pointer value is the same (i.e. check if they point to same object instance)

从Java 1.5(iirc)开始,有一个称为自动装箱(和拆箱)的功能,该功能使程序员可以在原始类型及其对应的包装器之间进行转换.

Starting from Java 1.5 (iirc), there is a feature called auto-boxing (and unboxing), which ease programmer in converting between primitive types and their corresponding wrapper.

过去,您需要执行以下操作:

In the past, you need to do something like this:

int a = 1234;
Integer intWrapper = new Integer(a);

int b = intWrapper.intValue();

使用自动装箱,您只需要编写:

With autoboxing, you just need to write:

int a = 1234;
Integer intWrapper = a;
int b = intWrapper;

然后编译器将其转换为:

And compiler is going to convert it to:

int a = 1234;
Integer intWrapper = Integer.valueOf(a);
int b = intWrapper.intValue();

到目前为止一切还好吗?

So far so good?

所以您的代码使用少量数字的原因是: Integer.valueOf()正在缓存经常使用的值.来自API文档:

So the reason why your code works with small number is: Integer.valueOf() is caching frequently-used value. From API doc:

公共静态整数valueOf(int i)

public static Integer valueOf(int i)

返回一个表示指定int值的Integer实例.如果不需要新的Integer实例,则通常应优先于构造方法Integer(int)使用此方法,因为此方法通过缓存经常请求的值可能会产生明显更好的空间和时间性能. 此方法将始终缓存-128至127(包括)范围内的值,并且可能会缓存该范围之外的其他值.

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

因为它正在缓存包装器,因此,如果您正在执行map.put(key,map.get(key) + 1),则转换为Integerget(key) + 1(即int)的结果(如果它是一个小数字)将是相同的相同int值的Integer实例.这意味着==仍然有效(因为变量指向相同的Integer).但是,如果它是未缓存的数字,则每个调用将是一个不同的实例,并且==将不起作用(因为变量指向Integer的不同实例,尽管Integer实例中的值相同)

Because it is caching the wrappers, therefore if you are doing map.put(key,map.get(key) + 1), result of get(key) + 1, which is an int, when converting to Integer and if it is a small number, will be a same instance of Integer for same int value. That means, == still works (as variables are pointing to same Integer). However if it is a not-cached number, every invocation will be a different instance, and == will not work (as variables are pointing to different instances of Integer, though the value in the Integer instances are the same)

关于算法的建议,尽管主题不多:

Suggestion to your algorithm, though a bit off topic:

您的逻辑过于复杂.可以大大简化为(伪代码):

Your logic is over complicated. It can be greatly simplified to (pseudo code):

countValley(String s) {
    currentLevel = 0
    valleyCount = 0
    for (step in s) {
        if step == 'U' {
            ++currentLevel;
            if (currentLevel == 0) {  // returning to sea level
                ++valleyCount
            }
        } else if step == 'D' {
            --currentLevel;
        }
    }
    return valleyCount
}        

这篇关于hashmap.get()==运算符返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆